<?php

namespace App\Http\Resources;

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

class CartResource 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,
            'status'       => $this->status?->value,
            'schedule_ids' => $this->whenLoaded('items', fn () => $this->items->pluck('schedule_id')->values()),
            'items'        => $this->whenLoaded('items', fn () => CartItemResource::collection($this->items)),

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

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

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