<?php

namespace Tests\Feature;

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

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

        $docxV1 = $this->fakeDocxWithBody('{{contract.reference}}');
        $this->post(route('admin.document-templates.store'), [
            'name' => 'Povzetek pogodbe',
            'slug' => 'contract-summary',
            'file' => $docxV1,
        ])->assertRedirect();

        $this->assertDatabaseHas('document_templates', [
            'slug' => 'contract-summary',
            'version' => 1,
        ]);

        $docxV2 = $this->fakeDocxWithBody('{{contract.reference}} {{generation.date}}');
        $this->post(route('admin.document-templates.store'), [
            'name' => 'Povzetek pogodbe',
            'slug' => 'contract-summary',
            'file' => $docxV2,
        ])->assertRedirect();

        $this->assertDatabaseHas('document_templates', [
            'slug' => 'contract-summary',
            'version' => 2,
        ]);

        $this->assertEquals(2, \App\Models\DocumentTemplate::where('slug', 'contract-summary')->count());
    }

    private function fakeDocxWithBody(string $body): UploadedFile
    {
        $tmp = tempnam(sys_get_temp_dir(), 'docx');
        $zip = new \ZipArchive;
        $zip->open($tmp, \ZipArchive::OVERWRITE);
        $zip->addFromString('[Content_Types].xml', '<Types></Types>');
        $zip->addFromString('word/document.xml', '<w:document><w:body>'.$body.'</w:body></w:document>');
        $zip->close();

        return UploadedFile::fake()->createWithContent('template.docx', file_get_contents($tmp));
    }
}
