<?php

declare(strict_types=1);

namespace Tests\Integration;

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

final class AppSubmitLegacyTest extends QdbTestCase
{
    public function testLegacySubmitAcceptsRetiredQuestionAfterBump(): void
    {
        $login = $this->api()->loginMobileAndGetToken(
            DatabaseSeeder::COACH_USERNAME,
            DatabaseSeeder::PASSWORD
        );
        $f = $this->fixture();

        $this->assertApiOk($this->submitQuestionnaireAs(
            $login['token'],
            $f->questionnaireId,
            $f->clientCode,
            [['questionID' => $f->questionShortId, 'answerOptionKey' => 'yes']],
            null,
            null,
            1
        ));

        require_once dirname(__DIR__, 2) . '/lib/questionnaire_structure.php';
        [$pdo, $tmpDb, $lockFp] = qdb_open(true);
        $rev = qdb_bump_structure_revision($pdo, $f->questionnaireId, 'legacy_test_retire');
        qdb_retire_question($pdo, $f->questionId, $rev);
        $currentRev = qdb_questionnaire_structure_revision($pdo, $f->questionnaireId);
        qdb_save($tmpDb, $lockFp);

        $this->assertGreaterThan(1, $currentRev);

        $res = $this->submitQuestionnaireAs(
            $login['token'],
            $f->questionnaireId,
            $f->clientCode,
            [['questionID' => $f->questionShortId, 'answerOptionKey' => 'yes']],
            null,
            null,
            1
        );
        $this->assertApiOk($res);
        $this->assertTrue($res['data']['submitted'] ?? false);
        $this->assertTrue($res['data']['legacySubmit'] ?? false);
        $this->assertSame(1, $res['data']['structureRevision'] ?? null);

        [$pdo, $tmpDb, $lockFp] = qdb_open(false);
        $sub = $pdo->prepare(
            'SELECT structureRevision, structureSnapshotJson FROM questionnaire_submission
             WHERE clientCode = :cc AND questionnaireID = :qn ORDER BY version DESC LIMIT 1'
        );
        $sub->execute([':cc' => $f->clientCode, ':qn' => $f->questionnaireId]);
        $row = $sub->fetch(\PDO::FETCH_ASSOC);
        $this->assertSame(1, (int)($row['structureRevision'] ?? 0));
        $snap = json_decode($row['structureSnapshotJson'] ?? '{}', true) ?: [];
        $this->assertNotEmpty($snap['questions'] ?? []);

        $archived = $pdo->prepare(
            'SELECT COUNT(*) FROM client_answer_submission cas
             INNER JOIN questionnaire_submission qs ON qs.submissionID = cas.submissionID
             WHERE qs.clientCode = :cc AND qs.questionnaireID = :qn AND cas.questionID = :qid'
        );
        $archived->execute([
            ':cc' => $f->clientCode,
            ':qn' => $f->questionnaireId,
            ':qid' => $f->questionId,
        ]);
        $this->assertGreaterThan(0, (int)$archived->fetchColumn());

        qdb_discard($tmpDb, $lockFp);
    }
}
