<?php

namespace Tests\Feature;

use App\Models\Action;
use App\Models\Activity;
use App\Models\ClientCase;
use App\Models\Contract;
use App\Models\Decision;
use App\Models\Document;
use App\Models\EmailLog;
use App\Models\EmailTemplate;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class EmailAttachmentsTest extends TestCase
{
    use RefreshDatabase;

    public function test_activity_with_attachments_queues_email_with_attachments(): void
    {
        Storage::fake('public');

        // Auth with baseline permissions
        $perm = Permission::firstOrCreate(['slug' => 'read'], ['name' => 'Read']);
        $role = Role::firstOrCreate(['slug' => 'admin'], ['name' => 'Admin']);
        $role->permissions()->syncWithoutDetaching([$perm->id]);
        $user = User::factory()->create();
        $user->roles()->syncWithoutDetaching([$role->id]);
        $this->actingAs($user);

        // Minimal domain graph: case -> contract
        $case = ClientCase::factory()->create();
        // Create a person email that is eligible to receive auto mails for the CLIENT's person
        $case->load('client.person');
        \App\Models\Email::factory()->create([
            'person_id' => $case->client->person->id,
            'receive_auto_mails' => true,
            'is_active' => true,
        ]);
        $action = Action::factory()->create();
        $decision = Decision::factory()->create(['auto_mail' => true]);
        $action->decisions()->attach($decision->id);
        $contract = Contract::factory()->create(['client_case_id' => $case->id]);

        // Template allowing attachments and requiring contract entity context
        $template = EmailTemplate::create([
            'name' => 'Attach OK',
            'key' => 'attach-ok',
            'subject_template' => 'Subj',
            'html_template' => '<p>Hello</p>',
            'text_template' => 'Hello',
            'entity_types' => ['contract'],
            'allow_attachments' => true,
            'active' => true,
        ]);
        // Bind template to decision
        \DB::table('decisions')->where('id', $decision->id)->update(['email_template_id' => $template->id]);

        // Seed a document belonging to the contract
        Storage::disk('public')->put('docs/a.txt', 'abc');
        $doc = new Document([
            'uuid' => (string) \Str::uuid(),
            'name' => 'a.txt',
            'original_name' => 'a.txt',
            'disk' => 'public',
            'path' => 'docs/a.txt',
            'file_name' => 'a.txt',
            'extension' => 'txt',
            'mime_type' => 'text/plain',
            'size' => 3,
            'is_public' => true,
        ]);
        $contract->documents()->save($doc);

        // Exercise: create activity with attachment_document_ids
        $response = $this->post(route('clientCase.activity.store', ['client_case' => $case->uuid]), [
            'action_id' => $action->id,
            'decision_id' => $decision->id,
            'contract_uuid' => $contract->uuid,
            'send_auto_mail' => true,
            'attachment_document_ids' => [$doc->id],
        ]);

        $response->assertSessionHasNoErrors();

        // Validate activity created and email queued with attachments
        $activity = Activity::latest()->first();
        $this->assertNotNull($activity);
        $this->assertEquals($action->id, $activity->action_id);
        $this->assertEquals($decision->id, $activity->decision_id);

        $log = EmailLog::latest()->first();
        $this->assertNotNull($log);
        $this->assertIsArray($log->attachments);
        $this->assertCount(1, $log->attachments);
        $this->assertEquals('docs/a.txt', $log->attachments[0]['path'] ?? null);
    }
}
