<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/** @mixin \App\Models\Task */
class TaskResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'description' => $this->description,
            'status' => $this->status,
            'priority' => $this->priority,
            'estimated_hours' => (float) $this->estimated_hours,
            'tracked_hours' => (float) $this->tracked_hours,
            'sort_order' => $this->sort_order,
            'parent_id' => $this->parent_id,
            'starts_at' => $this->starts_at,
            'due_at' => $this->due_at,
            'reminder_at' => $this->reminder_at,
            'completed_at' => $this->completed_at,
            'subtasks_count' => $this->whenCounted('subtasks'),
            'done_subtasks_count' => $this->whenCounted('doneSubtasks'),
            'parent' => [
                'id' => $this->parent_id,
                'title' => $this->whenLoaded('parent', fn () => $this->parent?->title),
            ],
            'deal' => [
                'id' => $this->deal_id,
                'title' => $this->whenLoaded('deal', fn () => $this->deal?->title),
            ],
            'project' => [
                'id' => $this->project_id,
                'name' => $this->whenLoaded('project', fn () => $this->project?->name),
            ],
            'project_stage' => [
                'id' => $this->project_stage_id,
                'name' => $this->whenLoaded('projectStage', fn () => $this->projectStage?->name),
            ],
            'company' => CompanyResource::make($this->whenLoaded('company')),
            'contact' => ContactResource::make($this->whenLoaded('contact')),
            'creator' => UserResource::make($this->whenLoaded('creator')),
            'assignee' => UserResource::make($this->whenLoaded('assignee')),
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}
