<?php

declare(strict_types=1);

namespace Tests\Integration;

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

final class QuestionnaireImportExportTest extends QdbTestCase
{
    public function testExportImportRoundTripPreservesQuestionnaire(): void
    {
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $f = $this->fixture();

        $export = $this->api()->withToken($token, 'GET', 'export', null, ['bundle' => '1']);
        $this->assertRawOk($export, 'application/json');
        $bundle = json_decode($export['body'], true, 512, JSON_THROW_ON_ERROR);
        $this->assertGreaterThanOrEqual(1, $bundle['questionnaireCount'] ?? 0);

        $del = $this->api()->withToken($token, 'DELETE', 'questionnaires', [
            'questionnaireID' => $f->questionnaireId,
        ]);
        $this->assertApiOk($del);

        $list = $this->api()->withToken($token, 'GET', 'questionnaires');
        $ids = array_column($list['data']['questionnaires'], 'questionnaireID');
        $this->assertNotContains($f->questionnaireId, $ids);

        $import = $this->api()->withToken($token, 'POST', 'questionnaires', [
            'action'          => 'importBundle',
            'bundle'          => $bundle,
            'replaceIfExists' => true,
        ]);
        $this->assertApiOk($import);
        $this->assertGreaterThanOrEqual(1, $import['data']['imported'] ?? 0);

        $questions = $this->api()->withToken($token, 'GET', 'questions', null, [
            'questionnaireID' => $f->questionnaireId,
        ]);
        $this->assertApiOk($questions);
        $qIds = array_column($questions['data']['questions'], 'questionID');
        $this->assertContains($f->questionId, $qIds);
        $this->assertContains($f->freeTextQuestionId, $qIds);
    }

    public function testAdminCreatesAndUpdatesQuestionnaire(): void
    {
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];

        $create = $this->api()->withToken($token, 'POST', 'questionnaires', [
            'name'    => 'Imported via API',
            'version' => '2',
            'state'   => 'draft',
        ]);
        $this->assertApiOk($create);
        $newId = $create['data']['questionnaire']['questionnaireID'] ?? '';
        $this->assertNotSame('', $newId);

        $update = $this->api()->withToken($token, 'PUT', 'questionnaires', [
            'questionnaireID' => $newId,
            'name'            => 'Renamed questionnaire',
            'state'           => 'active',
        ]);
        $this->assertApiOk($update);
        $this->assertSame('Renamed questionnaire', $update['data']['questionnaire']['name'] ?? '');
        $this->assertSame('active', $update['data']['questionnaire']['state'] ?? '');
    }
}
