<?php

namespace Tests\Feature\Admin;

use App\Models\LegalDocument;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class LegalDocumentManagementTest extends TestCase
{
    use RefreshDatabase;

    public function test_admin_can_update_legal_documents(): void
    {
        $admin = User::factory()->admin()->create();

        $payload = [
            'documents' => collect(LegalDocument::keys())
                ->map(fn (string $key): array => [
                    'key' => $key,
                    'title' => LegalDocument::defaults()[$key]['title'],
                    'body' => '<h2>Contenido vigente</h2><p>Texto legal actualizado.</p>',
                ])
                ->all(),
        ];

        $this->actingAs($admin)
            ->put(route('admin.legal-documents.update'), $payload)
            ->assertRedirect(route('admin.legal-documents.edit'));

        $this->assertDatabaseHas('legal_documents', [
            'key' => LegalDocument::TERMS_KEY,
            'body' => '<h2>Contenido vigente</h2><p>Texto legal actualizado.</p>',
        ]);
    }

    public function test_guest_cannot_access_legal_document_admin(): void
    {
        $this->get(route('admin.legal-documents.edit'))
            ->assertRedirect(route('login'));
    }

    public function test_legal_document_html_is_sanitized_before_storage(): void
    {
        $admin = User::factory()->admin()->create();

        $payload = [
            'documents' => collect(LegalDocument::keys())
                ->map(fn (string $key): array => [
                    'key' => $key,
                    'title' => LegalDocument::defaults()[$key]['title'],
                    'body' => '<p onclick="alert(1)">Acepto</p><section><script>alert(1)</script><p>Seguro</p></section><a href="javascript:alert(1)">link</a>',
                ])
                ->all(),
        ];

        $this->actingAs($admin)
            ->put(route('admin.legal-documents.update'), $payload)
            ->assertRedirect(route('admin.legal-documents.edit'));

        $body = LegalDocument::forKey(LegalDocument::TERMS_KEY)->body;

        $this->assertStringContainsString('<p>Acepto</p>', $body);
        $this->assertStringContainsString('<p>Seguro</p>', $body);
        $this->assertStringNotContainsString('onclick', $body);
        $this->assertStringNotContainsString('script', $body);
        $this->assertStringNotContainsString('javascript:', $body);
    }

    public function test_public_legal_document_page_is_available_without_login(): void
    {
        $document = LegalDocument::forKey(LegalDocument::PRIVACY_KEY);

        $this->get(route('legal-documents.show', $document))
            ->assertOk();
    }
}
