<?php
declare(strict_types=1);

namespace Celena\Core\Database\Driver;

final class MysqlDriver implements DriverInterface
{
    public function name(): string { return 'mysql'; }

    public function dsn(array $config): string
    {
        $host = $config['host'] ?? '127.0.0.1';
        $port = $config['port'] ?? 3306;
        $name = $config['name'] ?? '';
        $charset = $config['charset'] ?? 'utf8mb4';
        return "mysql:host=$host;port=$port;dbname=$name;charset=$charset";
    }

    public function quoteId(string $id): string
    {
        return implode('.', array_map(fn ($p) => '`' . str_replace('`', '``', $p) . '`', explode('.', $id)));
    }

    public function mapType(string $abstract, array $opts = []): string
    {
        return match ($abstract) {
            'id'        => 'BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY',
            'string'    => 'VARCHAR(' . ($opts['length'] ?? 255) . ')',
            'text'      => 'TEXT',
            'integer'   => 'INT',
            'bigInteger'=> 'BIGINT',
            'boolean'   => 'TINYINT(1)',
            'json'      => 'JSON',
            'datetime'  => 'DATETIME',
            'date'      => 'DATE',
            'float'     => 'DOUBLE',
            'decimal'   => 'DECIMAL(' . ($opts['precision'] ?? 10) . ',' . ($opts['scale'] ?? 2) . ')',
            'binary'    => 'BLOB',
            default     => strtoupper($abstract),
        };
    }

    public function supportsReturning(): bool { return false; }

    public function lastInsertSeq(string $table, string $column = 'id'): ?string { return null; }
}
