<?php

namespace App\Http\Resources;

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

class SprintResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $totalTasks = $this->whenLoaded('tasks', fn () => $this->tasks->count(), 0);
        $completedTasks = $this->whenLoaded('tasks', fn () => $this->tasks->where('status', 'done')->count(), 0);
        $remainingTasks = max($totalTasks - $completedTasks, 0);

        return [
            'id' => $this->id,
            'title' => $this->title,
            'project_id' => $this->project_id,
            'project' => new ProjectResource($this->whenLoaded('project')),
            'goal' => $this->goal,
            'capacity_hours' => $this->capacity_hours,
            'start_date' => $this->start_date?->format('Y-m-d'),
            'end_date' => $this->end_date?->format('Y-m-d'),
            'status' => $this->status,
            'tasks' => TaskResource::collection($this->whenLoaded('tasks')),
            'members' => UserResource::collection($this->whenLoaded('members')),
            'retrospective' => $this->whenLoaded('retrospective', fn () => [
                'went_well' => $this->retrospective?->went_well,
                'problems' => $this->retrospective?->problems,
                'improvements' => $this->retrospective?->improvements,
            ]),
            'total_tasks' => $totalTasks,
            'completed_tasks' => $completedTasks,
            'remaining_tasks' => $remainingTasks,
            'progress' => $totalTasks > 0 ? round(($completedTasks / $totalTasks) * 100, 2) : 0,
            'completed_at' => $this->completed_at?->toDateTimeString(),
            'completion_summary' => $this->completion_summary,
            'created_by' => $this->created_by,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}
