<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\ScheduledTaskRun;

class ScheduledTaskRunResource extends JsonResource
{
    /**
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request): array
    {
        /** @var ScheduledTaskRun $run */
        $run = $this->resource;

        return [
            'id' => $run->id,
            'task_id' => $run->scheduled_task_id,
            'task_name' => $run->task?->name,
            'status' => $run->status,
            'trigger' => $run->trigger,
            'scheduled_for' => $run->scheduled_for?->format('Y-m-d H:i'),
            'started_at' => $run->started_at?->format('Y-m-d H:i:s'),
            'finished_at' => $run->finished_at?->format('Y-m-d H:i:s'),
            'duration_seconds' => $run->started_at && $run->finished_at
                ? (int) $run->started_at->diffInSeconds($run->finished_at, true)
                : null,
            'triggered_by_run_id' => $run->triggered_by_run_id,
            'action_results' => $run->action_results ?? [],
            'error' => $run->error,
            'can_retry' => $run->status === ScheduledTaskRun::STATUS_FAILED,
        ];
    }
}
