<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonCommon\Migrations;

use Shopware\Plugins\ViisonCommon\Components\Migration\Migration;
use Shopware\Plugins\ViisonCommon\Components\Migration\MigrationTranscript;
use Zend_Db_Adapter_Abstract;

/**
 * Finds the document type with the given name and sets its key to the given value.
 *
 * Migration is executable since Shopware 5.5.0.
 */
class DocumentNameToDocumentKeyMigration implements Migration
{
    /**
     * @var Zend_Db_Adapter_Abstract
     */
    private $db;

    /**
     * @var string
     */
    private $name;

    /**
     * @var string
     */
    private $key;

    /**
     * @param string $name
     * @param string $key
     * @param Zend_Db_Adapter_Abstract $db
     */
    public function __construct($name, $key, \Zend_Db_Adapter_Abstract $db)
    {
        $this->db = $db;
        $this->name = $name;
        $this->key = $key;
    }

    /**
     * @inheritdoc
     */
    public function canExecute()
    {
        // Property Shopware\Models\Document\Document::key exists since SW 5.5.0
        return method_exists('Shopware\\Models\\Document\\Document', 'getKey');
    }

    /**
     * @inheritdoc
     */
    public function execute(MigrationTranscript $transcript)
    {
        $documentWithKeyExists = $this->db->fetchOne(
            'SELECT COUNT(`id`)
            FROM `s_core_documents`
            WHERE `key` = :key',
            [
                'key' => $this->key,
            ]
        );
        if ($documentWithKeyExists) {
            // This case that does not leave the system in a broken state, as the plugins
            // usually can continue their work with no problem. Just log a warning.
            $transcript->getLogger()->warning(sprintf(
                'Migration: Could not set key "%s" for document type with name "%s" because a type with this key already exists.',
                $this->key,
                $this->name
            ), [
                'migrationClass' => get_class($this),
            ]);

            return;
        }

        $this->db->query(
            'UPDATE `s_core_documents`
            SET `key` = :key
            WHERE `name` = :name
            LIMIT 1',
            [
                'key' => $this->key,
                'name' => $this->name,
            ]
        );
    }
}
