<?php

namespace App\Http\Resources;

use App\Models\ServicePackage;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class ServicePackageResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id'           => $this->id,
            'client_id'    => $this->client_id,
            'provider_id'  => $this->provider_id,
            'provider'     => $this->whenLoaded('provider', fn () => new ProviderResource($this->provider)),
            'status'       => $this->status?->value,
            'schedule_ids' => $this->whenLoaded('items', fn () => $this->items->pluck('schedule_id')->values()),
            'items'        => $this->whenLoaded('items', fn () => ServicePackageItemResource::collection($this->items)),

            'schedules' => $this->whenLoaded('items', fn () => ScheduleResource::collection(
                $this->items->pluck('schedule')->filter()->values(),
            )),

            'total_amount' => $this->whenLoaded('items', fn () =>
                (float) $this->items
                    ->filter(fn($item) => $item->schedule && ! in_array($item->schedule->status, ['cancelled', 'rejected'], true))
                    ->sum(fn($item) => (float) $item->schedule->total_amount)
            ),

            'created_at'   => $this->created_at?->toISOString(),
            'updated_at'   => $this->updated_at?->toISOString(),
        ];
    }

    /**
     * @param \Illuminate\Database\Eloquent\Collection<ServicePackage> $resource
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection<ServicePackageResource>
     */
    public static function collection($resource): AnonymousResourceCollection
    {
        return parent::collection($resource);
    }
}
