<?php

namespace App\Http\Resources;

use App\Facades\Settings;
use App\Http\Resources\VehicleAction\LoadsVehicleActions;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\Vehicle;

class VehicleQuickViewResource extends JsonResource
{
    use LoadsVehicleActions;

    public static $wrap = '';

    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    #[\Override]
    public function toArray($request)
    {
        return [
            'id' => $this->resource->id,
            'title' => $this->resource->title,
            'derivative' => $this->resource->derivative,
            'slug' => $this->resource->slug,
            'is_new' => $this->resource->is_new,
            'price' => $this->resource->price,
            'monthly_price' => $this->resource->monthly_price,
            'make_id' => $this->resource->make_id,
            'thumbnail' => [
                'small' => $this->resource->getPreviewImage('325x250'),
            ],
            'actions' => $this->getVehicleActions($this->resource),
            'odometer_mi' => $this->resource->odometer_mi,
            'odometer_km' => $this->resource->odometer_km,
            'registration_number' => $this->resource->registration_number,
            'first_registration_date' => $this->resource->first_registration_date?->format('Y-m-d'),
            'make_name' => $this->resource->make?->name,
            'model_name' => $this->resource->model?->name,
            'fuel_type' => $this->resource->fuelType?->name,
            'transmission' => $this->resource->transmission?->name,
            'body_style' => $this->resource->bodyStyle?->name,
            'make' => Settings::get('automotive-vehicle-brand-on-filter-card')
                ? [
                    'name' => $this->resource->make->name ?? '',
                    'logo' => $this->resource->make->logo ?? '',
                ]
                : null,
            'location' => $this->locationValue($this->resource),
            'deposit' => $this->resource->deposit,
            'is_reserved' => $this->resource->is_reserved,
            'finance_example' => $this->getFinanceExample($this->resource),
        ];
    }

    private function locationValue(Vehicle $vehicle): string
    {
        if (tenant()->hasMultipleLocations()) {
            return $vehicle->dealership->name ?? '';
        }

        return '';
    }

    private function getFinanceExample(Vehicle $vehicle)
    {
        if (Settings::get('vehicle-list-load-finance-example')) {
            return $vehicle->defaultFinanceExample;
        }

        return null;
    }
}
