<?php

declare(strict_types=1);

namespace Tests\Unit;

use Tests\Support\QdbTestCase;

final class QuestionnaireStructureTest extends QdbTestCase
{
    public function testBumpIncrementsRevisionAndStoresSnapshot(): void
    {
        require_once dirname(__DIR__, 2) . '/lib/questionnaire_structure.php';
        [$pdo, $tmpDb, $lockFp] = qdb_open(true);
        $f = $this->fixture();

        $before = qdb_questionnaire_structure_revision($pdo, $f->questionnaireId);
        $newRev = qdb_bump_structure_revision($pdo, $f->questionnaireId, 'test_bump');
        $after = qdb_questionnaire_structure_revision($pdo, $f->questionnaireId);

        $this->assertSame($before + 1, $newRev);
        $this->assertSame($newRev, $after);

        $manifest = qdb_load_structure_manifest($pdo, $f->questionnaireId, $before);
        $this->assertNotNull($manifest);
        $this->assertNotEmpty($manifest['questions'] ?? []);
        $this->assertSame($before, (int)($manifest['structureRevision'] ?? 0));

        qdb_save($tmpDb, $lockFp);
    }

    public function testRetirePreservesClientAnswers(): void
    {
        require_once dirname(__DIR__, 2) . '/lib/questionnaire_structure.php';
        $this->assertApiOk($this->submitFixtureQuestionnaire());

        [$pdo, $tmpDb, $lockFp] = qdb_open(true);
        $f = $this->fixture();

        $this->assertTrue(qdb_question_has_client_data($pdo, $f->questionId));
        $rev = qdb_bump_structure_revision($pdo, $f->questionnaireId, 'retire_test');
        qdb_retire_question($pdo, $f->questionId, $rev);

        $row = $pdo->prepare('SELECT retiredAt FROM question WHERE questionID = :id');
        $row->execute([':id' => $f->questionId]);
        $this->assertGreaterThan(0, (int)$row->fetchColumn());

        $ans = $pdo->prepare(
            'SELECT COUNT(*) FROM client_answer WHERE clientCode = :cc AND questionID = :qid'
        );
        $ans->execute([':cc' => $f->clientCode, ':qid' => $f->questionId]);
        $this->assertSame(1, (int)$ans->fetchColumn());

        qdb_save($tmpDb, $lockFp);
    }
}
