<?php

declare(strict_types=1);

namespace Tests\Integration;

use Tests\Support\DatabaseSeeder;
use Tests\Support\QdbTestCase;

final class BackupDevOpsTest extends QdbTestCase
{
    public function testAdminBackupCreatesCopyOfDatabase(): void
    {
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $res = $this->api()->withToken($token, 'POST', 'backup');
        $this->assertApiOk($res);
        $filename = $res['data']['filename'] ?? '';
        $this->assertNotSame('', $filename);

        $path = QDB_UPLOADS_DIR . '/backups/' . $filename;
        $this->assertFileExists($path);
        $this->assertGreaterThan(0, filesize($path));
        $this->assertSame(filesize(QDB_PATH), filesize($path));
    }

    public function testDevImportEmptyFixtureSucceeds(): void
    {
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $res = $this->api()->withToken($token, 'POST', 'dev', [
            'fixture' => [
                'fixtureVersion'  => 2,
                'prefix'          => 'dev_',
                'defaultPassword' => 'DevPass1!',
                'admins'          => [],
                'supervisors'     => [],
                'coaches'         => [],
                'clients'         => [],
            ],
        ]);
        $this->assertApiOk($res);
        $this->assertSame(0, $res['data']['imported']['clients'] ?? -1);
    }

    public function testDevRejectsInvalidFixtureVersion(): void
    {
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $res = $this->api()->withToken($token, 'POST', 'dev', [
            'fixture' => [
                'fixtureVersion'  => 99,
                'prefix'          => 'dev_',
                'defaultPassword' => 'DevPass1!',
            ],
        ]);
        $this->assertApiError($res, 'INVALID_FIELD', 400);
    }

    public function testMigrationAddsCategoryKeyColumn(): void
    {
        [$pdo, $tmpDb, $lockFp] = qdb_open(true);
        if (!qdb_column_exists($pdo, 'questionnaire', 'categoryKey')) {
            $this->markTestSkipped('categoryKey already absent in fresh schema');
        }
        $pdo->exec('ALTER TABLE questionnaire DROP COLUMN categoryKey');
        qdb_save($tmpDb, $lockFp);

        [$pdo2, $tmp2, $lock2] = qdb_open(false);
        $this->assertTrue(qdb_column_exists($pdo2, 'questionnaire', 'categoryKey'));
        qdb_discard($tmp2, $lock2);
    }

}
