<?php

namespace App\Http\Resources;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\VehicleReservations\Reservation;

class ReservationList extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    #[\Override]
    public function toArray(Request $request): array
    {
        if ($this->resource instanceof LengthAwarePaginator) {
            $this->resource
                ->through(fn(Reservation $reservation) => $this->mapReservation($reservation));
        } else {
            $this->resource = $this->resource
                ->map(fn(Reservation $reservation) => $this->mapReservation($reservation));
            return parent::toArray($request);
        }

        $data = parent::toArray($request);
        $data['default_columns'] = [
            'vehicle_description',
            'confirmed_at',
        ];

        return $data;
    }

    private function mapReservation(Reservation $reservation): array
    {
        return [
            'image' => [
                'src' => $reservation->vehicle?->getPreviewImage('mini-thumb'),
                'alt' => $reservation->vehicle?->title,
            ],
            'active' => true,
            'status' => $reservation->status,
            'title' => $reservation->name,
            'description' => $reservation->vehicle?->title,
            'registration_number' => $reservation->vehicle?->registration_number,
            'dealership_name' => $reservation->vehicle?->dealership?->name,
            'metaItems' => [
                'vehicle_description' => $this->getDescription($reservation),
                'confirmed_at' => $reservation->confirmed_at->format('d/m/Y H:i'),
            ],
            'link' => '/reservations/view/' . $reservation->id,
            'id' => $reservation->id,
        ];
    }

    private function getDescription(Reservation $reservation): string
    {
        $description = $reservation->data['vehicle']['description'] ?? '';

        if (empty($description)) {
            $description = collect([
                    $reservation->vehicle?->registration_number,
                    $reservation->vehicle?->make?->name ?? '',
                    $reservation->vehicle?->model?->name ?? '',
                    $reservation->vehicle?->derivative,
                    $reservation->vehicle?->price,
                ])
                ->filter()
                ->implode(' ');
        }

        return $description;
    }
}
