<?php

declare(strict_types=1);

namespace App\Http\Resources;

use App\Models\HealthTreatment;
use App\Support\FileUrl;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class HealthTreatmentResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'project_id' => $this->project_id,
            'product_id' => $this->product_id,
            'producer_id' => $this->producer_id,
            'initial_report_id' => $this->initial_report_id,
            'product_code' => $this->product_code,
            'product_name' => $this->product_name,
            'breed_name' => $this->breed_name,
            'disease_name' => $this->disease_name,
            'status' => $this->status,
            'status_label' => HealthTreatment::statusOptions()[(string) $this->status] ?? $this->status,
            'progress_percent' => (int) $this->progress_percent,
            'weight' => $this->weight !== null ? (float) $this->weight : null,
            'started_at' => $this->started_at?->toISOString(),
            'ended_at' => $this->ended_at?->toISOString(),
            'next_visit_at' => $this->next_visit_at?->toDateString(),
            'attachments' => $this->formatFiles($this->attachments),
            'notes' => $this->notes,
            'created_at' => $this->created_at?->toISOString(),
            'updated_at' => $this->updated_at?->toISOString(),
            'project' => new ProjectSummaryResource($this->whenLoaded('project')),
            'product' => new ProductResource($this->whenLoaded('product')),
            'producer' => new ProducerResource($this->whenLoaded('producer')),
            'initial_report' => new ReportResource($this->whenLoaded('initialReport')),
            'updates' => HealthTreatmentUpdateResource::collection($this->whenLoaded('updates')),
            'latest_update' => $this->when(
                $this->relationLoaded('updates') && $this->updates->isNotEmpty(),
                fn () => new HealthTreatmentUpdateResource($this->updates->first())
            ),
        ];
    }

    private function formatFiles(?array $files): ?array
    {
        if ($files === null) {
            return null;
        }

        return array_map(
            fn ($file) => is_string($file) ? FileUrl::url($file) : null,
            $files
        );
    }
}
