<?php

use App\Models\DocumentTemplate;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

use function Pest\Laravel\actingAs;
use function Pest\Laravel\post;

// Intentionally call Pest helpers with fully-qualified names in-body to satisfy static analyzers

it('auto-detects custom tokens and sets default types on upload', function () {
    Storage::fake('public');
    $admin = User::factory()->create();
    $perm = Permission::firstOrCreate(['slug' => 'manage-document-templates'], ['name' => 'Manage Document Templates']);
    $role = Role::firstOrCreate(['slug' => 'admin'], ['name' => 'Administrator']);
    $role->permissions()->syncWithoutDetaching([$perm->id]);
    $admin->roles()->syncWithoutDetaching([$role->id]);
    actingAs($admin);

    // Build minimal DOCX with a custom token {{custom.km_driven}}
    $tmp = tempnam(sys_get_temp_dir(), 'docx');
    $zip = new ZipArchive;
    $zip->open($tmp, ZipArchive::CREATE | ZipArchive::OVERWRITE);
    $zip->addFromString('word/document.xml', '<w:document>{{custom.km_driven}}</w:document>');
    $zip->close();
    $file = new UploadedFile($tmp, 'custom.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', null, true);

    post('/admin/document-templates', [
        'name' => 'Custom Test',
        'slug' => 'custom-test',
        'file' => $file,
    ])->assertRedirect();

    $tpl = DocumentTemplate::where('slug', 'custom-test')->latest('version')->first();
    expect($tpl)->not->toBeNull();
    expect($tpl->tokens)->toBeArray()->and($tpl->tokens)->toContain('custom.km_driven');
    $types = $tpl->meta['custom_default_types'] ?? [];
    expect($types)->toBeArray();
    expect($types)->toHaveKey('km_driven');
    expect($types['km_driven'])->toBe('string');
});
