<?php

namespace App\Exports;

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

class AutoTraderCSVExport implements FromCollection, WithHeadings
{
    use UsesSalesChannelRules;

    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        return Vehicle::query()
            ->with([
                'mediaUses.media',
                'dealership',
                'make',
                'model',
                'transmission',
                'fuelType',
                'bodyStyle',
                'features',
                'equipment'
            ])
            ->exportable()
            ->when(
                Settings::get('automotive-sales-channels-auto-trader-unpublish-sold'),
                fn($query) => $query->where('is_sold', '!=', 1)
            )
            ->when(
                Settings::get('automotive-sales-channels-auto-trader-unpublish-reserved'),
                fn($query) => $query->where('is_reserved', '!=', 1)
            )
            ->when(
                $this->hasSalesChannelRules(SalesChannelType::AUTOTRADER),
                fn($query) => $this->applyQueryConditionsForChannel($query, SalesChannelType::AUTOTRADER)
            )
            ->get()
            ->map(function (Vehicle $vehicle) {
                $vehicleData = [
                    'Feed_Id' => $vehicle->dealership?->data['auto-trader-location-id']
                        ?? Settings::get('auto-trader-advertiser-id'),
                    'Vehicle_ID' => $vehicle->uuid,
                    'FullRegistration' => $vehicle->vrm_condensed,
                    '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,
                    'ServiceHistory' => 'Y',
                    'Owners' => $vehicle->previous_owner_count,
                    'Category' => $this->getVehicleCategory($vehicle->type),
                    'FourWheelDrive',
                    'options' => $vehicle->features->count()
                        ? $vehicle->features->pluck('name')->implode(',')
                        : $vehicle->equipment->pluck('description')->implode(','),
                    'Comments' => $vehicle->description,
                    'Origin' => 'UK',
                    'V5' => 'Y',
                    'Condition' => $vehicle->is_new ? 'New' : 'Used',
                    'ExDemo' => $vehicle->is_demo ? 'Y' : 'N',
                    'FranchiseApproved' => 'Y',
                    'Attention_Grabber' => Str::limit($vehicle->attention_grabber, 27),
                    'Price_VAT_Status' => (strtolower($vehicle->type) == 'lcv') ? 'Ex VAT' : null
                ];

                if (!Settings::get('auto-trader-stock-remove-vehicles-images')) {
                    $vehicleData['picturerefs'] = $vehicle->mediaUses
                        ->filter(fn($mediaUse) => $mediaUse->media)
                        ->map(fn(MediaUse $mediaUse) => $mediaUse->media->getOriginalUrlAttribute(true))
                        ->implode(',');
                }

                return $vehicleData;
            });
    }

    /**
     * Heading row
     *
     * @return string[]
     */
    public function headings(): array
    {
        $headings = [
            'Feed_Id',
            'Vehicle_ID',
            'FullRegistration',
            'Colour',
            'FuelType',
            'Year',
            'Mileage',
            'BodyType',
            'Doors',
            'Make',
            'Model',
            'Variant',
            'EngineSize',
            'Price',
            'Transmission',
            'ServiceHistory',
            'Owners',
            'Category',
            'FourWheelDrive',
            'Options',
            'Comments',
            'Origin',
            'V5',
            'Condition',
            'ExDemo',
            'FranchiseApproved',
            'Attention_Grabber',
            'Price_VAT_Status'
        ];

        if (!Settings::get('auto-trader-stock-remove-vehicles-images')) {
            $headings[] = 'PictureRefs';
        }

        return $headings;
    }

    private function getVehicleCategory(string $vehicle_type): string
    {
        return match (strtolower($vehicle_type)) {
            'lcv' => 'COMM',
            'motorcycle' => 'BIKE',
            default => 'CARS',
        };
    }
}
