<?php

namespace Tests\Tenant;

use App\Mail\ScheduledTaskSummaryMail;
use App\ScheduledTasks\ActionResult;
use App\ScheduledTasks\Actions\SendEmailAction;
use App\ScheduledTasks\TaskRunContext;
use Illuminate\Support\Facades\Mail;
use Mtc\MercuryDataModels\ScheduledTask;
use Mtc\MercuryDataModels\ScheduledTaskRun;
use Tests\TenantTestCase;

class SendEmailActionTest extends TenantTestCase
{
    public function testQueuesTheSummaryEmailWithInterpolatedSubject(): void
    {
        Mail::fake();

        $task = ScheduledTask::factory()->create(['name' => 'Nightly export']);
        $run = ScheduledTaskRun::factory()->create(['scheduled_task_id' => $task->id]);
        $context = new TaskRunContext($run);
        $context->push('export-map', ActionResult::completed('Export map "Feed" run'));

        $result = app(SendEmailAction::class)->execute([
            'recipients' => ['dealer@example.test', 'sales@example.test'],
            'subject' => '{task} finished on {date}',
            'template' => 'task-summary',
            'include_chain_results' => true,
        ], $context);

        $this->assertEquals('completed', $result->status);
        Mail::assertQueued(ScheduledTaskSummaryMail::class, function (ScheduledTaskSummaryMail $mail) {
            return str_contains($mail->subjectLine, 'Nightly export finished on')
                && count($mail->chainResults) === 1
                && $mail->hasTo('dealer@example.test')
                && $mail->hasTo('sales@example.test');
        });
    }

    public function testChainResultsAreOmittedWhenToggleIsOff(): void
    {
        Mail::fake();

        $run = ScheduledTaskRun::factory()->create();
        $context = new TaskRunContext($run);
        $context->push('export-map', ActionResult::completed('done'));

        app(SendEmailAction::class)->execute([
            'recipients' => ['dealer@example.test'],
            'subject' => 'Plain',
            'template' => 'task-summary',
            'include_chain_results' => false,
        ], $context);

        Mail::assertQueued(
            ScheduledTaskSummaryMail::class,
            fn (ScheduledTaskSummaryMail $mail) => $mail->chainResults === []
        );
    }

    public function testTemplateRendersChainRows(): void
    {
        $mail = new ScheduledTaskSummaryMail(
            subjectLine: 'Summary',
            taskName: 'Nightly export',
            chainResults: [
                ['action' => 'export-map', 'status' => 'completed', 'message' => 'Feed run', 'stats' => []],
                ['action' => 'send-email', 'status' => 'failed', 'message' => 'SMTP down', 'stats' => []],
            ],
        );

        $rendered = $mail->render();

        $this->assertStringContainsString('Nightly export', $rendered);
        $this->assertStringContainsString('Feed run', $rendered);
        $this->assertStringContainsString('SMTP down', $rendered);
    }
}
