<?php

namespace Tests\Feature;

use App\Models\Contract;
use App\Models\DocumentSetting;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

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

        // Upload minimal template
        $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', '<w:document><w:body>{{contract.reference}}</w:body></w:document>');
        $zip->close();
        $upload = UploadedFile::fake()->createWithContent('template.docx', file_get_contents($tmp));
        $this->post(route('admin.document-templates.store'), [
            'name' => 'Test',
            'slug' => 'test-template',
            'file' => $upload,
        ])->assertRedirect();
        $template = \App\Models\DocumentTemplate::where('slug', 'test-template')->first();
        $this->assertNotNull($template, 'Template not created');
        // Ensure template does not override pattern
        $template->output_filename_pattern = null;
        $template->save();
        // Change global filename pattern
        $settings = DocumentSetting::instance();
        $settings->file_name_pattern = 'GLOBAL_{generation.date}_{version}_{slug}.docx';
        $settings->save();

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

        $doc = \App\Models\Document::latest('id')->first();
        $this->assertNotNull($doc);
        $this->assertStringStartsWith('GLOBAL_', $doc->file_name);
        $this->assertStringContainsString('v1_', $doc->file_name, 'Version placeholder not applied');
    }
}
