<?php

declare(strict_types=1);

namespace Tests\Integration;

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

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

        $this->api()->withToken($token, 'PUT', 'translations', [
            'type'         => 'language',
            'languageCode' => 'es',
            'name'         => 'Spanish',
        ]);
        $this->api()->withToken($token, 'PUT', 'translations', [
            'type'         => 'question',
            'id'           => $f->questionId,
            'languageCode' => 'es',
            'text'         => 'Consentimiento',
        ]);

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

        $this->api()->withToken($token, 'DELETE', 'translations', [
            'type'         => 'question',
            'id'           => $f->questionId,
            'languageCode' => 'es',
        ]);

        $import = $this->api()->withToken($token, 'POST', 'translations', [
            'action' => 'importBundle',
            'bundle' => $bundle,
        ]);
        $this->assertApiOk($import);

        $get = $this->api()->withToken($token, 'GET', 'translations', null, [
            'type' => 'question',
            'id'   => $f->questionId,
        ]);
        $es = null;
        foreach ($get['data']['translations'] as $row) {
            if ($row['languageCode'] === 'es') {
                $es = $row['text'];
            }
        }
        $this->assertSame('Consentimiento', $es);
    }

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

        $this->api()->withToken($token, 'PUT', 'translations', [
            'type'         => 'language',
            'languageCode' => 'it',
            'name'         => 'Italian',
        ]);
        $del = $this->api()->withToken($token, 'DELETE', 'translations', [
            'type'         => 'language',
            'languageCode' => 'it',
        ]);
        $this->assertApiOk($del);

        $langs = $this->api()->withToken($token, 'GET', 'translations', null, ['languages' => '1']);
        $codes = array_column($langs['data']['languages'], 'languageCode');
        $this->assertNotContains('it', $codes);
    }
}
