<?php

declare(strict_types=1);

namespace Tests\Integration;

use Tests\Support\QdbTestCase;

final class DbInitTest extends QdbTestCase
{
    public function testEncryptedDbRoundTrip(): void
    {
        $this->assertFileExists(QDB_PATH);
        [$pdo1, $t1, $l1] = qdb_open(false);
        $count1 = (int)$pdo1->query('SELECT COUNT(*) FROM users')->fetchColumn();
        qdb_discard($t1, $l1);

        [$pdo2, $t2, $l2] = qdb_open(true);
        $pdo2->exec("INSERT INTO language (languageCode, name) VALUES ('fr', 'French') "
            . qdb_upsert_do_nothing(['languageCode']));
        qdb_save($t2, $l2);

        [$pdo3, $t3, $l3] = qdb_open(false);
        $fr = $pdo3->query("SELECT name FROM language WHERE languageCode = 'fr'")->fetchColumn();
        qdb_discard($t3, $l3);
        $this->assertSame('French', $fr);
        $this->assertGreaterThan(0, $count1);
    }

    public function testSystemSettingTableExists(): void
    {
        [$pdo, $tmp, $lock] = qdb_open(false);
        $this->assertTrue(qdb_table_exists($pdo, 'system_setting'));
        $this->assertTrue(qdb_table_exists($pdo, 'session'));
        qdb_discard($tmp, $lock);
    }

    public function testSchemaSqlContentIsExecutedDirectly(): void
    {
        $pdo = new \PDO('sqlite::memory:');
        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

        qdb_exec_schema_sql($pdo, 'CREATE TABLE schema_sql_test (id INTEGER PRIMARY KEY);');

        $this->assertTrue(qdb_table_exists($pdo, 'schema_sql_test'));
    }

    public function testRuntimeDriverOverrideWinsOverConfiguration(): void
    {
        qdb_env_override('QDB_DRIVER', 'mysql');
        $this->assertSame('mysql', qdb_env_get('QDB_DRIVER'));
        $this->assertTrue(qdb_is_mysql());

        qdb_env_override('QDB_DRIVER', 'sqlite');
        $this->assertTrue(qdb_is_sqlite());
    }

    public function testMigrationsRecreateDroppedSubmissionTables(): void
    {
        [$pdo, $tmp, $lock] = qdb_open(true);
        $pdo->exec('DROP TABLE IF EXISTS client_answer_submission');
        $pdo->exec('DROP TABLE IF EXISTS questionnaire_submission');
        qdb_save($tmp, $lock);

        [$pdo2, $tmp2, $lock2] = qdb_open(false);
        $this->assertTrue(qdb_table_exists($pdo2, 'questionnaire_submission'));
        $this->assertTrue(qdb_table_exists($pdo2, 'client_answer_submission'));
        qdb_discard($tmp2, $lock2);

        $this->assertFileExists(QDB_PATH);
    }
}
