<?php

namespace App\Extensions\Installed\Importer\Services\DatabaseAdapters;

abstract class AbstractDatabaseImportAdapter implements DatabaseImportAdapter
{
    protected ?\PDO $connection = null;
    protected array $dbConfig = [];
    protected array $options = [];
    protected string $prefix = '';

    public function boot(array $dbConfig, array $options = []): void
    {
        $this->dbConfig = $dbConfig;
        $this->options = $options;
        $this->prefix = $dbConfig['prefix'] ?? '';

        $this->connection = $this->connect($dbConfig);
    }

    public function connection(): \PDO
    {
        if (!$this->connection) {
            throw new \RuntimeException('Adapter connection has not been initialised.');
        }

        return $this->connection;
    }

    public function prefix(): string
    {
        return $this->prefix;
    }

    public function tableExists(string $table): bool
    {
        $qualified = $this->prefix . $table;

        $stmt = $this->connection()->prepare("
            SELECT COUNT(*)
              FROM information_schema.TABLES
             WHERE TABLE_SCHEMA = DATABASE()
               AND TABLE_NAME = :table
        ");
        $stmt->bindValue(':table', $qualified);
        $stmt->execute();

        return (bool) $stmt->fetchColumn();
    }

    public function columnExists(string $table, string $column): bool
    {
        $qualified = $this->prefix . $table;

        $stmt = $this->connection()->prepare("
            SELECT COUNT(*)
              FROM information_schema.COLUMNS
             WHERE TABLE_SCHEMA = DATABASE()
               AND TABLE_NAME = :table
               AND COLUMN_NAME = :column
        ");
        $stmt->bindValue(':table', $qualified);
        $stmt->bindValue(':column', $column);
        $stmt->execute();

        return (bool) $stmt->fetchColumn();
    }

    protected function connect(array $config): \PDO
    {
        $dsn = sprintf(
            'mysql:host=%s;port=%s;dbname=%s;charset=utf8mb4',
            $config['host'] ?? 'localhost',
            $config['port'] ?? 3306,
            $config['database']
        );

        return new \PDO(
            $dsn,
            $config['username'],
            $config['password'] ?? null,
            [
                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
                \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
            ]
        );
    }

    /**
     * Helper to build prefixed table names.
     */
    protected function table(string $table): string
    {
        return $this->prefix . $table;
    }
}