<?php

declare(strict_types=1);

namespace App\Core;

use PDO;
use PDOException;

class Database
{
    private static ?PDO $pdo = null;
    private static bool $schemaReady = false;

    public static function enabled(): bool
    {
        return strtolower((string) self::env('DB_CONNECTION', 'file')) === 'mysql';
    }

    public static function pdo(): PDO
    {
        if (self::$pdo instanceof PDO) {
            return self::$pdo;
        }

        $host = (string) self::env('DB_HOST', '127.0.0.1');
        $port = (string) self::env('DB_PORT', '3306');
        $database = (string) self::env('DB_DATABASE', '');
        $username = (string) self::env('DB_USERNAME', '');
        $password = (string) self::env('DB_PASSWORD', '');
        $charset = (string) self::env('DB_CHARSET', 'utf8mb4');

        if ($database === '' || $username === '') {
            throw new PDOException('Configure DB_DATABASE e DB_USERNAME no ficheiro .env.');
        }

        $dsn = "mysql:host={$host};port={$port};dbname={$database};charset={$charset}";

        self::$pdo = new PDO($dsn, $username, $password, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ]);

        return self::$pdo;
    }

    public static function ensureSchema(): void
    {
        if (self::$schemaReady) {
            return;
        }

        self::pdo()->exec(
            "CREATE TABLE IF NOT EXISTS app_records (
                id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
                collection VARCHAR(100) NOT NULL,
                record_id BIGINT UNSIGNED NOT NULL,
                payload LONGTEXT NOT NULL,
                created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (id),
                UNIQUE KEY app_records_collection_record_unique (collection, record_id),
                KEY app_records_collection_index (collection)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
        );

        self::$schemaReady = true;
    }

    private static function env(string $key, mixed $default = null): mixed
    {
        if (array_key_exists($key, $_ENV)) {
            return $_ENV[$key];
        }

        if (array_key_exists($key, $_SERVER)) {
            return $_SERVER[$key];
        }

        $value = getenv($key);

        return $value === false ? $default : $value;
    }
}
