<?php

declare(strict_types=1);

namespace Tests\Unit;

use Tests\Support\JsonErrorResponse;
use Tests\Support\QdbTestCase;

final class CommonBundleTest extends QdbTestCase
{
    public function testImportQuestionnairesBundleRejectsEmptyList(): void
    {
        [$pdo, $tmpDb, $lockFp] = qdb_open(true);
        try {
            qdb_import_questionnaires_bundle($pdo, ['questionnaires' => []]);
            $this->fail('Expected JsonErrorResponse');
        } catch (JsonErrorResponse $e) {
            $this->assertSame('MISSING_FIELDS', $e->errorCode);
        } finally {
            qdb_discard($tmpDb, $lockFp);
        }
    }

    public function testImportTranslationsBundleRoundTripOnPdo(): void
    {
        [$pdo, $tmpDb, $lockFp] = qdb_open(true);
        $f = $this->fixture();
        qdb_put_translation($pdo, 'question', $f->questionId, 'en', 'Hello EN');
        qdb_save($tmpDb, $lockFp);

        [$pdo2, $tmp2, $lock2] = qdb_open(false);
        $bundle = qdb_export_translations_bundle($pdo2);
        qdb_discard($tmp2, $lock2);

        [$pdo3, $tmp3, $lock3] = qdb_open(true);
        $pdo3->prepare('DELETE FROM question_translation WHERE questionID = :id AND languageCode = :lc')
            ->execute([':id' => $f->questionId, ':lc' => 'en']);
        $result = qdb_import_translations_bundle($pdo3, $bundle);
        qdb_save($tmp3, $lock3);
        $this->assertGreaterThan(0, $result['imported'] ?? 0);

        [$pdo4, $tmp4, $lock4] = qdb_open(false);
        $stmt = $pdo4->prepare(
            'SELECT text FROM question_translation WHERE questionID = :id AND languageCode = :lc'
        );
        $stmt->execute([':id' => $f->questionId, ':lc' => 'en']);
        $this->assertSame('Hello EN', $stmt->fetchColumn());
        qdb_discard($tmp4, $lock4);
    }

    public function testExportQuestionnaireBundleIncludesQuestionKeys(): void
    {
        [$pdo, $tmpDb, $lockFp] = qdb_open(false);
        $f = $this->fixture();
        $item = qdb_export_questionnaire_bundle($pdo, $f->questionnaireId);
        qdb_discard($tmpDb, $lockFp);
        $this->assertNotNull($item);
        $keys = array_column($item['questions'], 'questionKey');
        $this->assertContains('consent_q', $keys);
    }
}
