<?php

namespace App\Http\Resources;

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

class VehiclePrintResource extends JsonResource
{
    use FormatAsCurrency;

    #[\Override]
    public function toArray($request)
    {
        $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,
            'door_count' => $vehicle->door_count,
            'manufacture_year' => $vehicle->manufacture_year,
            'colour' => $vehicle->colour,
            'mileage' => $vehicle->odometer_mi,
            'dealership_name' => $vehicle->dealership?->name,
        ];
    }

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