<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Installer\Migration;

use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Table;
use Gls\GlsPoland\PrestaShop\Installer\DatabaseMigrationInterface;

abstract class AbstractMigration implements DatabaseMigrationInterface
{
    private $dbPrefix;
    private $dbEngine;

    public function __construct(string $dbPrefix, string $dbEngine)
    {
        $this->dbPrefix = $dbPrefix;
        $this->dbEngine = $dbEngine;
    }

    public function down(Schema $schema): void
    {
    }

    protected function getEngine(): string
    {
        return $this->dbEngine;
    }

    protected function prefixTableName(string $name): string
    {
        return $this->dbPrefix . $name;
    }

    protected function createTable(Schema $schema, string $name): Table
    {
        $name = $this->prefixTableName($name);
        if ($schema->hasTable($name)) {
            return $schema->getTable($name);
        }

        return $schema
            ->createTable($name)
            ->addOption('engine', $this->dbEngine);
    }

    protected function dropTable(Schema $schema, string $name): void
    {
        $name = $this->prefixTableName($name);
        if ($schema->hasTable($name)) {
            $schema->dropTable($name);
        }
    }

    protected function addColumn(Table $table, string $name, string $type): Column
    {
        if ($table->hasColumn($name)) {
            return $table->getColumn($name);
        }

        return $table->addColumn($name, $type);
    }

    protected function setPrimaryKey(Table $table, array $columns): void
    {
        $primaryKey = $table->getPrimaryKey();
        if (null !== $primaryKey) {
            if ($columns === $primaryKey->getColumns()) {
                return;
            }

            $table->dropPrimaryKey();
        }

        $table->setPrimaryKey($columns);
    }
}
