<?php

namespace App\Services\Database;

use App\Contracts\DatabaseDriverInterface;
use App\Contracts\SchemaDiscoveryInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;

class MySqlDriver implements DatabaseDriverInterface, SchemaDiscoveryInterface
{
    protected string $connectionName = 'mariavel_dynamic';

    public function connect(array $config): bool
    {
        Config::set("database.connections.{$this->connectionName}", [
            'driver' => 'mysql',
            'host' => $config['host'] ?? '127.0.0.1',
            'port' => $config['port'] ?? '3306',
            'database' => $config['database'] ?? null,
            'username' => $config['username'] ?? 'root',
            'password' => $config['password'] ?? '',
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ]);

        try {
            DB::purge($this->connectionName);
            DB::connection($this->connectionName)->getPdo();
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    public function query(string $sql, array $bindings = []): array
    {
        return DB::connection($this->connectionName)->select($sql, $bindings);
    }

    public function getConnection()
    {
        return DB::connection($this->connectionName);
    }

    public function getDatabases(): array
    {
        $results = $this->query('SHOW DATABASES');
        return array_map(fn($db) => $db->Database, $results);
    }

    public function getTables(): array
    {
        $results = $this->query('SHOW TABLES');
        $key = "Tables_in_" . DB::connection($this->connectionName)->getDatabaseName();
        return array_map(fn($table) => $table->$key, $results);
    }

    public function getTableSchema(string $table): array
    {
        return $this->query("DESCRIBE `{$table}`");
    }

    public function getForeignKeys(string $table): array
    {
        $sql = "
            SELECT 
                COLUMN_NAME, 
                REFERENCED_TABLE_NAME, 
                REFERENCED_COLUMN_NAME 
            FROM 
                INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
            WHERE 
                TABLE_NAME = ? AND 
                REFERENCED_TABLE_NAME IS NOT NULL AND 
                TABLE_SCHEMA = ?
        ";
        
        $dbName = DB::connection($this->connectionName)->getDatabaseName();
        return $this->query($sql, [$table, $dbName]);
    }
}
