<?php

namespace App\Http\Resources;

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

class VehicleMoveRequestList 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 (VehicleMoveRequest $moveRequest) => $this->mapMoveRequest($moveRequest));
        } else {
            $this->resource = $this->resource
                ->map(fn (VehicleMoveRequest $moveRequest) => $this->mapMoveRequest($moveRequest));
            return parent::toArray($request);
        }

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

        return $data;
    }

    private function mapMoveRequest(VehicleMoveRequest $moveRequest): array
    {
        return [
            'image' => [
                'src' => $moveRequest->vehicle?->getPreviewImage('mini-thumb'),
                'alt' => $moveRequest->vehicle?->title,
            ],
            'active' => $moveRequest->status !== 'cancelled',
            'status' => $moveRequest->status,
            'title' => $moveRequest->name,
            'description' => $moveRequest->vehicle?->title,
            'reference' => $moveRequest->reference,
            'uuid' => $moveRequest->vehicle?->uuid,
            'vrm_condensed' => $moveRequest->vehicle?->vrm_condensed,
            'from_dealership_name' => $moveRequest->fromDealership?->name,
            'to_dealership_name' => $moveRequest->toDealership?->name,
            'metaItems' => [
                'vehicle_description' => $this->getDescription($moveRequest),
                'from_dealership_name' => $moveRequest->fromDealership?->name,
                'to_dealership_name' => $moveRequest->toDealership?->name,
                'paid_at' => $moveRequest->paid_at?->format('d/m/Y H:i'),
            ],
            'link' => '/vehicle-move-requests/view/' . $moveRequest->id,
            'id' => $moveRequest->id,
        ];
    }

    private function getDescription(VehicleMoveRequest $moveRequest): string
    {
        return collect([
                $moveRequest->vehicle?->vrm_condensed,
                $moveRequest->vehicle?->make?->name ?? '',
                $moveRequest->vehicle?->model?->name ?? '',
                $moveRequest->vehicle?->derivative,
                $moveRequest->vehicle?->price,
            ])
            ->filter()
            ->implode(' ');
    }
}
