<?php

namespace Tests\Feature;

use App\Events\DocumentSettingsUpdated;
use App\Models\Contract;
use App\Models\DocumentSetting;
use App\Models\Role;
use App\Models\User;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;

class DocumentSettingsPoliciesTest extends TestCase
{
    private function baseTemplateUpload(string $xml): void
    {
        $tmp = tempnam(sys_get_temp_dir(), 'doc');
        $zip = new \ZipArchive;
        $zip->open($tmp, \ZipArchive::OVERWRITE);
        $zip->addFromString('[Content_Types].xml', '<Types></Types>');
        $zip->addFromString('word/document.xml', $xml);
        $zip->close();
        $contents = file_get_contents($tmp);
        \Storage::disk('public')->put('templates/policy-template.docx', $contents);
        $tmpl = new \App\Models\DocumentTemplate;
        $userId = auth()->id() ?? \App\Models\User::factory()->create()->id;
        $tmpl->fill([
            'name' => 'PolTest',
            'slug' => 'policy-template',
            'core_entity' => 'contract',
            'version' => 1,
            'engine' => 'docx',
            'file_path' => 'templates/policy-template.docx',
            'file_hash' => sha1($contents),
            'file_size' => strlen($contents),
            'mime_type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'active' => true,
            'output_filename_pattern' => null,
            'fail_on_unresolved' => false,
            'entities' => [],
            'columns' => [],
            'tokens' => [],
            'created_by' => $userId,
            'updated_by' => $userId,
        ]);
        $tmpl->save();
    }

    public function test_unresolved_policy_blank_and_keep(): void
    {
        $user = User::factory()->create();
        $role = Role::firstOrCreate(['slug' => 'admin'], ['name' => 'Admin']);
        $user->roles()->sync([$role->id]);
        $this->actingAs($user);

        $this->baseTemplateUpload('<w:document><w:body>{{contract.reference}} {{contract.unknown_field}}</w:body></w:document>');
        $contract = Contract::factory()->create(['reference' => 'ABC123']);

        $settings = DocumentSetting::instance();
        $settings->unresolved_policy = 'blank';
        $settings->save();
        app(\App\Services\Documents\DocumentSettings::class)->refresh();

        $resp = $this->postJson(route('contracts.generate-document', ['contract' => $contract->uuid]), [
            'template_slug' => 'policy-template',
        ]);
        $resp->assertOk();

        // Switch to keep and regenerate
        $settings->unresolved_policy = 'keep';
        $settings->save();
        app(\App\Services\Documents\DocumentSettings::class)->refresh();
        $resp2 = $this->postJson(route('contracts.generate-document', ['contract' => $contract->uuid]), [
            'template_slug' => 'policy-template',
        ]);
        $resp2->assertOk();
    }

    public function test_global_date_format_override_applies(): void
    {
        $user = User::factory()->create();
        $role = Role::firstOrCreate(['slug' => 'admin'], ['name' => 'Admin']);
        $user->roles()->sync([$role->id]);
        $this->actingAs($user);
        $this->baseTemplateUpload('<w:document><w:body>{{contract.start_date}}</w:body></w:document>');
        $contract = Contract::factory()->create(['start_date' => now()->toDateString()]);
        $settings = DocumentSetting::instance();
        $settings->date_formats = ['contract.start_date' => 'd.m.Y'];
        $settings->save();

        $resp = $this->postJson(route('contracts.generate-document', ['contract' => $contract->uuid]), [
            'template_slug' => 'policy-template',
        ]);
        $resp->assertOk();
    }

    public function test_settings_update_dispatches_event(): void
    {
        Event::fake();
        $user = User::factory()->create();
        $role = Role::firstOrCreate(['slug' => 'admin'], ['name' => 'Admin']);
        $user->roles()->sync([$role->id]);
        $this->actingAs($user);
        $settings = DocumentSetting::instance();
        $this->put(route('admin.document-settings.update'), [
            'file_name_pattern' => $settings->file_name_pattern,
            'date_format' => $settings->date_format,
            'unresolved_policy' => $settings->unresolved_policy,
            'preview_enabled' => $settings->preview_enabled,
            'whitelist' => $settings->whitelist,
            'date_formats' => $settings->date_formats,
        ])->assertRedirect();
        Event::assertDispatched(DocumentSettingsUpdated::class);
    }
}
