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', '');
$zip->addFromString('word/document.xml', '{{custom.order_id}}|{{custom.missing}}');
$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));
}
}