<?php

declare(strict_types=1);

namespace App\Http\Resources;

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

class HealthTreatmentUpdateResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'health_treatment_id' => $this->health_treatment_id,
            'report_at' => $this->report_at?->toISOString(),
            'progress_percent' => $this->progress_percent !== null ? (int) $this->progress_percent : null,
            'notes' => $this->notes,
            'expert_opinion' => $this->expert_opinion,
            'written_report' => $this->written_report,
            'attachments' => $this->formatFiles($this->attachments),
            'documents' => $this->formatFiles($this->documents),
            'total_cost' => $this->total_cost !== null ? (int) $this->total_cost : null,
            'invoice_image' => FileUrl::url($this->invoice_image),
            'created_at' => $this->created_at?->toISOString(),
            'consumables' => $this->whenLoaded('consumables', fn () => $this->consumables->map(fn ($c) => [
                'id' => $c->id,
                'name' => $c->name,
                'unit' => $c->unit,
                'quantity' => $c->quantity !== null ? (float) $c->quantity : null,
                'unit_price' => $c->unit_price !== null ? (int) $c->unit_price : null,
            ])),
            'invoice_items' => $this->whenLoaded('invoiceItems', fn () => $this->invoiceItems->map(fn ($i) => [
                'id' => $i->id,
                'title' => $i->title,
                'amount' => $i->amount !== null ? (int) $i->amount : null,
            ])),
            'creator' => new UserResource($this->whenLoaded('createdBy')),
        ];
    }

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

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