<?php

namespace Tests\Feature;

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

class DocumentGenerationTest extends TestCase
{
    public function test_admin_can_upload_template_and_generate_contract_document(): void
    {
        Storage::fake('public');

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

        // Minimal docx file (ZIP) with simple document.xml
        $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();
        $docxBytes = file_get_contents($tmp);
        $upload = UploadedFile::fake()->createWithContent('template.docx', $docxBytes);

        $this->actingAs($user);
        $resp = $this->post(route('admin.document-templates.store'), [
            'name' => 'Pogodba povzetek',
            'slug' => 'contract-summary',
            'file' => $upload,
        ]);
        $resp->assertRedirect();
        $this->assertDatabaseHas('document_templates', ['slug' => 'contract-summary']);

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

        $genResp = $this->postJson(route('contracts.generate-document', ['contract' => $contract->uuid]), [
            'template_slug' => 'contract-summary',
        ]);
        $genResp->assertOk()->assertJson(['status' => 'ok']);

        $this->assertDatabaseHas('documents', [
            'template_version' => 1,
        ]);
        $doc = \App\Models\Document::latest('id')->first();
        $this->assertTrue(Storage::disk('public')->exists($doc->path), 'Generated document file missing');
    }

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

        // Docx with invalid token {{contract.unknown_field}}
        $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.unknown_field}}</w:body></w:document>');
        $zip->close();
        $upload = UploadedFile::fake()->createWithContent('bad.docx', file_get_contents($tmp));

        $this->actingAs($user);
        $this->post(route('admin.document-templates.store'), [
            'name' => 'Neveljavna',
            'slug' => 'invalid-template',
            'file' => $upload,
        ])->assertRedirect();

        $contract = Contract::factory()->create();
        $resp = $this->postJson(route('contracts.generate-document', ['contract' => $contract->uuid]), [
            'template_slug' => 'invalid-template',
        ]);
        $resp->assertStatus(500); // runtime exception for unresolved token
    }
}
