<?php

namespace App\Exports;

use App\SalesChannelType;
use App\Traits\UsesSalesChannelRules;
use Illuminate\Support\Collection;
use Mtc\ContentManager\Models\MediaUse;
use Mtc\MercuryDataModels\Vehicle;

class OutAndAboutExport
{
    use UsesSalesChannelRules;

    public function getExportData(): Collection
    {
        return Vehicle::query()
                ->with([
                    'mediaUses.media',
                    'make',
                    'model',
                    'transmission',
                    'fuelType',
                    'bodyStyle',
                ])
                ->exportable()
                ->when(
                    $this->hasSalesChannelRules(SalesChannelType::OUT_AND_ABOUT),
                    fn($query) => $this->applyQueryConditionsForChannel($query, SalesChannelType::OUT_AND_ABOUT)
                )
                ->get()
                ->map(function (Vehicle $vehicle) {
                    return collect([
                        'StockNumber' => $vehicle->uuid,
                        // vehicle type: motorhome, campervan, caravan
                        'Type' => $vehicle->bodyStyle?->name,
                        'Manufacturer' => $vehicle->make?->name,

                        // TODO: range: required
                        // need to confirm how to get this, acceptable values...

                        'Model' => $vehicle->model?->name,
                        'RegistrationYear' => $vehicle->first_registration_date?->format('Y'),
                        'Mileage' => $vehicle->odometer_mi,
                        'Price' => $vehicle->price,
                        'Condition' => empty($vehicle->is_new) ? 'Used' : 'New',
                        'Width' => $vehicle->getCustom('width') ?? '',
                        'Height' => $vehicle->getCustom('height') ?? '',
                        'Length' => $vehicle->getCustom('length') ?? '',
                        'Berths' => $vehicle->getCustom('berths') ?? '',
                        'SteeringPosition' => $this->getSteeringPosition($vehicle->getCustom('driver-side') ?? ''),
                        'Fuel' => $vehicle->fuelType?->name,
                        'Gears' => $vehicle->transmission?->name,
                        'Images' => $vehicle->mediaUses
                            ->filter(fn($mediaUse) => $mediaUse->media)
                            ->map(fn(MediaUse $mediaUse) => $mediaUse->getUrl('large'))
                            ->implode(';'),
                    ]);
                });
    }

    private function getSteeringPosition(string $steering_position): string
    {
        return stripos($steering_position, 'left') === false
            ? 'Right'
            : 'Left';
    }
}
