<?php

namespace App\ScheduledTasks\Actions;

use App\Mail\ScheduledTaskSummaryMail;
use App\ScheduledTasks\ActionResult;
use App\ScheduledTasks\Contracts\TaskAction;
use App\ScheduledTasks\TaskRunContext;
use Illuminate\Support\Facades\Mail;

class SendEmailAction implements TaskAction
{
    /**
     * Fixed blade templates only: no user-authored HTML or blade is ever rendered,
     * which closes template injection entirely.
     */
    private const TEMPLATES = ['task-summary'];

    public function key(): string
    {
        return 'send-email';
    }

    public function label(): string
    {
        return __('scheduled_tasks.actions.send-email');
    }

    public function available(): bool
    {
        return true;
    }

    public function userSelectable(): bool
    {
        return true;
    }

    public function configFields(): array
    {
        return [
            [
                'key' => 'recipients',
                'type' => 'emails',
                'label' => __('scheduled_tasks.fields.recipients'),
            ],
            [
                'key' => 'subject',
                'type' => 'text',
                'label' => __('scheduled_tasks.fields.subject'),
                'helper' => __('scheduled_tasks.fields.subject_helper'),
            ],
            [
                'key' => 'template',
                'type' => 'select',
                'label' => __('scheduled_tasks.fields.template'),
                'options' => collect(self::TEMPLATES)
                    ->map(fn (string $template) => ['id' => $template, 'name' => ucwords(str_replace('-', ' ', $template))])
                    ->toArray(),
            ],
            [
                'key' => 'include_chain_results',
                'type' => 'boolean',
                'label' => __('scheduled_tasks.fields.include_chain_results'),
            ],
        ];
    }

    public function rules(array $config): array
    {
        return [
            'recipients' => ['required', 'array', 'min:1'],
            'recipients.*' => ['email'],
            'subject' => ['required', 'string', 'max:150'],
            'template' => ['required', 'in:' . implode(',', self::TEMPLATES)],
            'include_chain_results' => ['boolean'],
        ];
    }

    public function execute(array $config, TaskRunContext $context): ActionResult
    {
        $task = $context->run->task;

        $subject = str_replace(
            ['{task}', '{date}'],
            [$task?->name ?? 'Scheduled task', now()->format('d/m/Y')],
            $config['subject']
        );

        Mail::to($config['recipients'])->queue(new ScheduledTaskSummaryMail(
            subjectLine: $subject,
            taskName: $task?->name ?? 'Scheduled task',
            chainResults: !empty($config['include_chain_results']) ? $context->entries() : [],
        ));

        return ActionResult::completed(
            sprintf('Email queued to %d recipient(s)', count($config['recipients'])),
            ['recipients' => count($config['recipients'])]
        );
    }

    public function queue(): string
    {
        return 'emails';
    }
}
