<?php

namespace App\Exports;

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

class InventoryExport implements FromCollection, WithHeadings, WithStrictNullComparison
{
    use UsesSalesChannelRules;

    public function collection(): Enumerable
    {
        return Vehicle::query()
            ->with([
                'mediaUses.media',
                'dealership',
                'make',
                'model',
                'transmission',
                'fuelType',
                'bodyStyle',
                'drivetrain',
                'equipment',
            ])
            ->exportable()
            ->when(
                $this->hasSalesChannelRules(SalesChannelType::INVENTORY),
                fn ($query) => $this->applyQueryConditionsForChannel($query, SalesChannelType::INVENTORY)
            )
            ->get()
            ->map(function (Vehicle $vehicle) {
                $photoTimestamp = $vehicle->mediaUses
                    ->sortByDesc('updated_at')
                    ->first()
                    ?->updated_at
                    ->format('Y-m-d H:i:s');

                return [
                    'Dealer ID' => $vehicle->dealership?->data['inventory-dealer-id'] ?? null,
                    'Dealer Name' => $vehicle->dealership?->name,
                    'Is New' => $vehicle->is_new ? 'N' : 'U',
                    'Status' => $vehicle->is_reserved ? 'Reserved' : 'Instock',
                    'Note' => '',
                    'VIN' => $vehicle->vin,
                    'Stock #' => $vehicle->uuid,
                    'Year' => $vehicle->is_new ? ($vehicle->manufacture_year ?: 0) : $vehicle->manufacture_year,
                    'Make' => $vehicle->make?->name,
                    'Model' => $vehicle->model?->name,
                    'Trim' => $vehicle->derivative,
                    'Body Style' => $vehicle->bodyStyle?->name,
                    'Body Type' => $vehicle->type == VehicleType::LCV ? 'VCV' : 'CAR',
                    'Factory Certified' => '',
                    'Dealer Certified' => '',
                    'Model Code' => '',
                    'List Price' => $vehicle->price,
                    'Special Price' => $vehicle->price,
                    'Cost Price' => $vehicle->price,
                    'ExtraPrice1' => '',
                    'ExtraPrice2' => '',
                    'ExtraPrice3' => '',
                    'Mileage' => $vehicle->odometer_mi,
                    'Chrome Style ID' => '',
                    'Fuel Type' => $vehicle->fuelType?->name,
                    'Exterior color' => $vehicle->colour,
                    'Exterior Color Code' => '',
                    'Interior Color' => '',
                    'Interior Color Code' => '',
                    'Interior Material' => '',
                    'Wheelbase' => $vehicle->wheelbase_type,
                    'DoorCount' => $vehicle->door_count,
                    'EngineDisplacement' => $vehicle->engine_size_cc,
                    'Cylinders' => '',
                    'Engine' => '',
                    'Drivetrain' => $vehicle->drivetrain?->name,
                    'Transmission' => $vehicle->transmission?->name,
                    'Transmission Speed' => '',
                    'Option Description' => $vehicle->equipment
                        ->sortBy(fn ($item) => trim(($item->category ?? '') . ' ' . ($item->description ?? '')))
                        ->pluck('description')
                        ->map(fn ($description) => str_replace('|', ' ', trim((string) $description)))
                        ->filter()
                        ->implode('|'),
                    'Option code' => '',
                    'Photo URLs' => $vehicle->mediaUses
                        ->filter(fn ($mediaUse) => $mediaUse->media)
                        ->map(fn (MediaUse $mediaUse) => $mediaUse->getUrl('large'))
                        ->implode(','),
                    'Photo Timestamp' => $photoTimestamp ?? '',
                    'Dealer comments on vehicle' => '',
                    'In Stock Date' => $vehicle->date_in_stock,
                    'Last Modified Date' => $vehicle->updated_at->format('Y-m-d H:i:s'),
                    'Video URL' => $vehicle->main_video_url,
                    'City MPG' => $vehicle->mpg,
                    'Hwy MPG' => $vehicle->mpg,
                    'VDP Link' => Site::vehicleUrl($vehicle),
                    'Extra Field 1' => $vehicle->vrm_condensed,
                    'Extra Field 2' => '',
                    'Extra Field 3' => '',
                ];
            });
    }

    /**
     * Heading row
     *
     * @return string[]
     */
    public function headings(): array
    {
        return [
            'Dealer ID',
            'Dealer Name',
            'Is New',
            'Status',
            'Note',
            'VIN',
            'Stock #',
            'Year',
            'Make',
            'Model',
            'Trim',
            'Body Style',
            'Body Type',
            'Factory Certified',
            'Dealer Certified',
            'Model Code',
            'List Price',
            'Special Price',
            'Cost Price',
            'ExtraPrice1',
            'ExtraPrice2',
            'ExtraPrice3',
            'Mileage',
            'Chrome Style ID',
            'Fuel Type',
            'Exterior color',
            'Exterior Color Code',
            'Interior Color',
            'Interior Color Code',
            'Interior Material',
            'Wheelbase',
            'DoorCount',
            'EngineDisplacement',
            'Cylinders',
            'Engine',
            'Drivetrain',
            'Transmission',
            'Transmission Speed',
            'Option Description',
            'Option code',
            'Photo URLs',
            'Photo Timestamp',
            'Dealer comments on vehicle',
            'In Stock Date',
            'Last Modified Date',
            'Video URL',
            'City MPG',
            'Hwy MPG',
            'VDP Link',
            'Extra Field 1',
            'Extra Field 2',
            'Extra Field 3',
        ];
    }
}
