<?php
    namespace AxiumPHP\Core\Database\Drivers;

    use PDO;
    use PDOException;
    use RuntimeException;

    class Postgres extends PDOAbstract {

        public function __construct(string $envName, ?string $schema = null) {
            $this->connect(envName: $envName, schema: $schema);
        }

        protected function connect(string $envName, ?string $schema = null): void {
            $host   = $_ENV["{$envName}_DATABASE_HOST"];
            $port   = $_ENV["{$envName}_DATABASE_PORT"] ?? 5432;
            $dbname = $_ENV["{$envName}_DATABASE_NAME"];
            $user   = $_ENV["{$envName}_DATABASE_USERNAME"];
            $pass   = $_ENV["{$envName}_DATABASE_PASSWORD"];
            $schema = $schema ?? ($_ENV["{$envName}_DATABASE_SCHEMA"] ?? 'public');
            $systemTimeZone = $_ENV["SYSTEM_TIMEZONE"] ?? 'UTC';
            $sslMode = $_ENV["{$envName}_DATABASE_SSLMODE"] ?? 'disable'; // disable, require, verify-ca, verify-full

            $dsn = "pgsql:host={$host};port={$port};dbname={$dbname};sslmode={$sslMode}";

            try {
                $this->connection = new PDO(
                    dsn: $dsn,
                    username: $user,
                    password: $pass,
                    options: [
                        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                        PDO::ATTR_PERSISTENT => false
                    ]
                );

                // Define o fuso horário da sessão
                $this->connection->exec(statement: "SET TIME ZONE '{$systemTimeZone}'");

                // Define o schema padrão
                $this->connection->exec(statement: "SET search_path TO {$schema}, public");

            } catch (PDOException $e) {
                throw new RuntimeException(
                    message: "Erro ao conectar no PostgreSQL: {$e->getMessage()}"
                );
            }
        }

        // Método auxiliar para alterar schema dinamicamente
        public function setSchema(string $schema): void {
            $this->connection->exec(statement: "SET search_path TO {$schema}, public");
        }
    }