<?php

namespace App\Exports;

use App\SalesChannelType;
use App\Traits\UsesSalesChannelRules;
use Illuminate\Support\Enumerable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Mtc\ContentManager\Models\MediaUse;
use Mtc\MercuryDataModels\Vehicle;

class AaCarsExport implements FromCollection, WithHeadings
{
    use UsesSalesChannelRules;

    public function collection(): Enumerable
    {
        return Vehicle::query()
            ->with([
                'mediaUses.media',
                'dealership',
                'make',
                'model',
                'transmission',
                'fuelType',
                'bodyStyle',
                'specs',
            ])
            ->exportable()
            ->when(
                $this->hasSalesChannelRules(SalesChannelType::AA_CARS),
                fn ($query) => $this->applyQueryConditionsForChannel($query, SalesChannelType::AA_CARS)
            )
            ->get()
            ->map(fn (Vehicle $vehicle) => [
                'feedid' => $vehicle->dealership?->data['aa-cars-dealer-id'] ?? null,
                'vehicleid' => $vehicle->uuid,
                'registration' => $vehicle->registration_number,
                'colour' => $vehicle->colour,
                'fueltype' => $vehicle->fuelType?->name,
                'year' => $vehicle->manufacture_year,
                'mileage' => $vehicle->odometer_mi,
                'bodytype' => $vehicle->bodyStyle?->name,
                'doors' => $vehicle->door_count,
                'make' => $vehicle->make?->name,
                'model' => $vehicle->model?->name,
                'variant' => $vehicle->derivative,
                'enginesize' => $vehicle->engine_size_cc,
                'price' => $vehicle->price,
                'transmission' => $vehicle->transmission?->name,
                'description' => $vehicle->description,
                'options' => $vehicle->specs
                    ->pluck('description')
                    ->implode(','),
                'picturerefs' => $vehicle->mediaUses
                    ->filter(fn ($mediaUse) => $mediaUse->media)
                    ->map(fn (MediaUse $mediaUse) => $mediaUse->getUrl('large'))
                    ->implode(','),
                'plusvat' => (strtolower($vehicle->type) == 'lcv') ? 'Y' : 'N',
            ]);
    }

    /**
     * Heading row
     *
     * @return string[]
     */
    public function headings(): array
    {
        return [
            'feedid',
            'vehicleid',
            'registration',
            'colour',
            'fueltype',
            'year',
            'mileage',
            'bodytype',
            'doors',
            'make',
            'model',
            'variant',
            'enginesize',
            'price',
            'transmission',
            'description',
            'options',
            'picturerefs',
            'plusvat',
        ];
    }
}
