<?php

namespace Tests\Feature;

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

class DocumentCustomTokensTest extends TestCase
{
    public function test_custom_tokens_defaults_and_overrides(): void
    {
        Storage::fake('public');

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

        // Minimal docx with custom tokens
        $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>{{custom.order_id}}|{{custom.missing}}</w:body></w:document>');
        $zip->close();
        $bytes = file_get_contents($tmp);
        $upload = UploadedFile::fake()->createWithContent('template.docx', $bytes);

        // Store template via controller to ensure tokens/metadata recorded
        $resp = $this->post(route('admin.document-templates.store'), [
            'name' => 'Custom Test',
            'slug' => 'custom-test',
            'file' => $upload,
        ]);
        $resp->assertRedirect();

        // Add defaults via meta
        $template = DocumentTemplate::where('slug', 'custom-test')->orderByDesc('version')->firstOrFail();
        $template->meta = ['custom_defaults' => ['order_id' => 'DEF-123']];
        $template->save();

        $contract = Contract::factory()->create();

        // Call generation with override for order_id; missing should become empty by default
        $gen = $this->postJson(route('contracts.generate-document', ['contract' => $contract->uuid]), [
            'template_slug' => 'custom-test',
            'custom' => ['order_id' => 'OVR-999'],
        ]);
        $gen->assertOk()->assertJson(['status' => 'ok']);
        $doc = \App\Models\Document::latest('id')->first();
        $this->assertNotNull($doc);

        // For strictness, we could open the docx to verify replacements, but that is heavy.
        // A lighter check: ensure no unresolved/fail occurred and file exists.
        $this->assertTrue(Storage::disk('public')->exists($doc->path));
    }
}
