<?php

namespace App\Http\Resources;

use App\Facades\Settings;
use App\Traits\FormatAsCurrency;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Vehicle;

class VehiclePrintResource extends JsonResource
{
    use FormatAsCurrency;

    /**
     * Whether the system has more than one dealership. When only a single
     * dealership exists the name is redundant on every row, so it is omitted.
     */
    protected bool $hasMultipleDealerships = false;

    #[\Override]
    public function toArray($request)
    {
        $this->hasMultipleDealerships = Dealership::query()->count() > 1;

        $this->resource = $this->resource
            ->map(fn (Vehicle $vehicle) => $this->mapVehicle($vehicle));

        return [
            'data' => $this->resource->toArray(),
            'site_logo' => $this->getSiteLogoUrl('site-logo'),
            'site_logo_alternate' => $this->getSiteLogoUrl('site-alternate-logo'),
        ];
    }

    private function getSiteLogoUrl(string $key): ?string
    {
        $logo = Settings::get($key);
        return $logo['url'] ?? null;
    }

    protected function mapVehicle(Vehicle $vehicle): array
    {
        return [
            'id' => $vehicle->id,
            'title' => $vehicle->title,
            'image' => $this->getVehicleImageSrc($vehicle),
            'registration_number' => $vehicle->registration_number,
            'price' => $this->asCurrency($vehicle->price ?? 0.0, tenant()->currency),
            'transmission' => $vehicle->transmission?->name,
            'fuel_type' => $vehicle->fuelType?->name,
            'derivative' => $vehicle->derivative,
            'door_count' => $vehicle->door_count,
            'manufacture_year' => $vehicle->manufacture_year,
            'colour' => $vehicle->colour,
            'mileage' => $vehicle->odometer_mi,
            'dealership_name' => $this->hasMultipleDealerships ? $vehicle->dealership?->name : null,
        ];
    }

    private function getVehicleImageSrc(Vehicle $vehicle): ?string
    {
        return $vehicle->getPreviewImage('mini-thumb');
    }
}
