<?php

namespace Tests\Feature;

use App\Models\Action;
use App\Models\Activity;
use App\Models\Contract;
use App\Models\Decision;
use App\Models\DocumentTemplate;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class DocumentTemplateActivityTest extends TestCase
{
    use RefreshDatabase;

    public function test_creates_activity_with_interpolated_note(): void
    {
        Storage::fake('public');
        $perm = Permission::firstOrCreate(['slug' => 'manage-document-templates'], ['name' => 'Manage Document Templates']);
        $readPerm = Permission::firstOrCreate(['slug' => 'read'], ['name' => 'Read']);
        $role = Role::firstOrCreate(['slug' => 'admin'], ['name' => 'Administrator']);
        $role->permissions()->syncWithoutDetaching([$perm->id, $readPerm->id]);
        $user = User::factory()->create();
        $user->roles()->syncWithoutDetaching([$role->id]);
        $this->actingAs($user);

        $segment = \App\Models\Segment::factory()->create();
        $action = Action::factory()->create(['segment_id' => $segment->id]);
        $decision = Decision::factory()->create();
        $action->decisions()->attach($decision->id);

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

        // Create simple DOCX file with one token
        $zip = new \ZipArchive;
        $tmp = tempnam(sys_get_temp_dir(), 'docx');
        $zip->open($tmp, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
        $zip->addFromString('word/document.xml', '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>{contract.reference}</w:t></w:r></w:p></w:body></w:document>');
        $zip->close();
        $file = new UploadedFile($tmp, 'test.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', null, true);

        $this->post('/admin/document-templates', [
            'name' => 'Activity Doc',
            'slug' => 'activity-doc',
            'file' => $file,
            'action_id' => $action->id,
            'decision_id' => $decision->id,
            'activity_note_template' => 'Generated doc for {contract.reference}',
        ])->assertSessionHasNoErrors();

        $template = DocumentTemplate::where('slug', 'activity-doc')->latest('version')->first();
        $this->assertNotNull($template);
        // Extra safety: update settings to ensure fields persist in case store skipped them
        $this->put(route('admin.document-templates.settings.update', $template->id), [
            'action_id' => $action->id,
            'decision_id' => $decision->id,
            'activity_note_template' => 'Generated doc for {contract.reference}',
        ])->assertSessionHasNoErrors();
        $template->refresh();
        $this->assertNotNull($template->activity_note_template);

        $this->post(route('contracts.generate-document', ['contract' => $contract->uuid]), [
            'template_slug' => 'activity-doc',
        ])->assertJson(['status' => 'ok']);

        $activity = Activity::latest()->first();
        $this->assertNotNull($activity);
        $this->assertEquals($action->id, $activity->action_id);
        $this->assertEquals($decision->id, $activity->decision_id);
        $this->assertStringContainsString($contract->reference, (string) $activity->note);
    }
}
