<?php

namespace App\Http\Resources;

use App\ScheduledTasks\ActionRegistry;
use App\ScheduledTasks\Contracts\TaskAction;
use App\ScheduledTasks\ScheduledTaskRepository;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\ScheduledTask;

class ScheduledTaskResource extends JsonResource
{
    /**
     * The platform's admin composables read the payload flat (no "data" envelope),
     * matching import/export maps.
     */
    public static $wrap = null;

    /**
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request): array
    {
        /** @var ScheduledTask $task */
        $task = $this->resource;

        return [
            'task' => [
                'id' => $task->id,
                'name' => $task->name,
                'managed_by' => $task->managed_by,
                'enabled' => $task->enabled,
                'overlap_policy' => $task->overlap_policy,
                'trigger_type' => $task->trigger_type,
                'parent_task_id' => $task->parent_task_id,
                'parent_condition' => $task->parent_condition,
                'event' => $task->event,
                'event_filter' => $task->event_filter,
                'schedule_rules' => $task->schedule_rules ?? [],
                'next_due_at' => $task->next_due_at?->format('Y-m-d H:i'),
                'last_run_at' => $task->last_run_at?->format('Y-m-d H:i'),
                'created_at' => $task->created_at?->format('Y-m-d H:i'),
                'updated_at' => $task->updated_at?->format('Y-m-d H:i'),
                'actions' => $task->actions->map(fn ($action) => [
                    'id' => $action->id,
                    'order' => $action->order,
                    'action_type' => $action->action_type,
                    'config' => $action->config ?? [],
                    'run_when' => $action->run_when,
                    'timeout_seconds' => $action->timeout_seconds,
                ]),
                'children' => $task->children->map(fn (ScheduledTask $child) => [
                    'id' => $child->id,
                    'name' => $child->name,
                    'parent_condition' => $child->parent_condition,
                    'last_outcome' => $child->runs()->finished()->latest('finished_at')->first()?->status,
                ]),
                'last_outcome' => $task->runs()
                    ->finished()
                    ->latest('finished_at')
                    ->first()?->status,
            ],
            'data_options' => $this->dataOptions($task),
        ];
    }

    private function dataOptions(ScheduledTask $task): array
    {
        return [
            'frequencies' => collect(ScheduledTask::FREQUENCIES)
                ->map(fn (string $frequency) => ['id' => $frequency, 'name' => ucfirst($frequency)])
                ->toArray(),
            'days_of_week' => collect([
                1 => 'Monday', 2 => 'Tuesday', 3 => 'Wednesday', 4 => 'Thursday',
                5 => 'Friday', 6 => 'Saturday', 7 => 'Sunday',
            ])->map(fn ($name, $id) => ['id' => $id, 'name' => $name])->values()->toArray(),
            'days_of_month' => collect(range(1, 31))
                ->map(fn (int $day) => ['id' => $day, 'name' => (string) $day])
                ->toArray(),
            'overlap_policies' => [
                ['id' => ScheduledTask::OVERLAP_SKIP, 'name' => 'Skip when previous run still going'],
                ['id' => ScheduledTask::OVERLAP_QUEUE, 'name' => 'Queue behind previous run'],
            ],
            // Used for the parent-task (after_task) condition, worded relative to the parent
            'conditions' => [
                ['id' => ScheduledTask::CONDITION_ON_SUCCESS, 'name' => 'When it succeeds'],
                ['id' => ScheduledTask::CONDITION_ON_FAILURE, 'name' => 'When it fails'],
                ['id' => ScheduledTask::CONDITION_ALWAYS, 'name' => 'Always'],
            ],
            // Used for an action's run condition, worded relative to the steps above it
            'action_conditions' => [
                ['id' => ScheduledTask::CONDITION_ON_SUCCESS, 'name' => 'When steps above succeed'],
                ['id' => ScheduledTask::CONDITION_ON_FAILURE, 'name' => 'When a step above fails'],
                ['id' => ScheduledTask::CONDITION_ALWAYS, 'name' => 'Always'],
            ],
            'trigger_types' => [
                ['id' => ScheduledTask::TRIGGER_SCHEDULE, 'name' => 'On a schedule'],
                ['id' => ScheduledTask::TRIGGER_AFTER_TASK, 'name' => 'After another task'],
                ['id' => ScheduledTask::TRIGGER_AFTER_EVENT, 'name' => 'After a platform event'],
            ],
            'events' => collect(config('scheduled_tasks.events', []))
                ->keys()
                ->map(fn (string $event) => ['id' => $event, 'name' => $event])
                ->toArray(),
            'action_types' => app(ActionRegistry::class)
                ->selectable()
                ->map(fn (TaskAction $action, string $key) => [
                    'id' => $key,
                    'name' => $action->label(),
                    'config_fields' => $action->configFields(),
                ])
                ->values()
                ->toArray(),
            'parent_tasks' => app(ScheduledTaskRepository::class)
                ->eligibleParents($task->exists ? $task : null)
                ->toArray(),
        ];
    }
}
