<?php

declare(strict_types=1);

namespace Tests\Integration;

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

final class ExportExtendedTest extends QdbTestCase
{
    public function testExportAllVersionsCsvIncludesBothSubmissions(): void
    {
        $login = $this->api()->loginMobileAndGetToken(
            DatabaseSeeder::COACH_USERNAME,
            DatabaseSeeder::PASSWORD
        );
        $f = $this->fixture();
        $this->assertApiOk($this->submitFixtureQuestionnaire());
        $this->submitQuestionnaireAs($login['token'], $f->questionnaireId, $f->clientCode, [
            ['questionID' => $f->questionShortId, 'answerOptionKey' => 'yes'],
        ]);

        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $res = $this->api()->withToken($token, 'GET', 'export', null, [
            'questionnaireID' => $f->questionnaireId,
            'allVersions'     => '1',
        ]);
        $this->assertRawOk($res, 'text/csv');
        $this->assertStringContainsString($f->clientCode, $res['body']);
        $lines = array_filter(explode("\n", trim($res['body'])));
        $this->assertGreaterThanOrEqual(3, count($lines), 'header plus at least two data rows');
    }

    public function testExportAllZipContainsCsvForSubmittedQuestionnaire(): void
    {
        if (!class_exists(ZipArchive::class)) {
            $this->markTestSkipped('php-zip extension not installed');
        }

        $this->submitFixtureQuestionnaire();
        $f = $this->fixture();
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];

        $res = $this->api()->withToken($token, 'GET', 'export', null, ['exportAll' => '1']);
        $this->assertRawOk($res, 'application/zip');

        $zipPath = sys_get_temp_dir() . '/qdb_test_export_' . bin2hex(random_bytes(4)) . '.zip';
        file_put_contents($zipPath, $res['body']);
        $zip = new ZipArchive();
        $this->assertTrue($zip->open($zipPath) === true);
        $this->assertGreaterThanOrEqual(1, $zip->numFiles);
        $foundCsv = false;
        for ($i = 0; $i < $zip->numFiles; $i++) {
            $name = $zip->getNameIndex($i);
            if (is_string($name) && str_ends_with(strtolower($name), '.csv')) {
                $csv = $zip->getFromIndex($i);
                if (is_string($csv) && str_contains($csv, $f->clientCode)) {
                    $foundCsv = true;
                    break;
                }
            }
        }
        $zip->close();
        @unlink($zipPath);
        $this->assertTrue($foundCsv, 'ZIP should contain a CSV with submitted client code');
    }

    public function testCoachForbiddenOnPerQuestionnaireCsvExport(): void
    {
        $this->submitFixtureQuestionnaire();
        $token = $this->api()->loginMobileAndGetToken(
            DatabaseSeeder::COACH_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $f = $this->fixture();
        $res = $this->api()->withMobileToken($token, 'GET', 'export', null, [
            'questionnaireID' => $f->questionnaireId,
        ]);
        $this->assertApiError($res, 'FORBIDDEN', 403);
    }

    public function testExportAllWithAllVersionsZip(): void
    {
        if (!class_exists(\ZipArchive::class)) {
            $this->markTestSkipped('php-zip extension not installed');
        }
        $login = $this->api()->loginMobileAndGetToken(
            DatabaseSeeder::COACH_USERNAME,
            DatabaseSeeder::PASSWORD
        );
        $f = $this->fixture();
        $this->submitFixtureQuestionnaire();
        $this->submitQuestionnaireAs($login['token'], $f->questionnaireId, $f->clientCode, [
            ['questionID' => $f->questionShortId, 'answerOptionKey' => 'yes'],
        ]);

        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $res = $this->api()->withToken($token, 'GET', 'export', null, [
            'exportAll'   => '1',
            'allVersions' => '1',
        ]);
        $this->assertRawOk($res, 'application/zip');
        $this->assertStringStartsWith('PK', $res['body']);
    }
}
