<?php

namespace App\Http\Controllers;

use App\Facades\Settings;
use App\Facades\Site;
use App\Http\Requests\PhyronNotificationRequest;
use App\Http\Requests\PhyronStockRequest;
use App\Jobs\ImportImageListNotificationJob;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Mtc\ContentManager\Models\MediaUse;
use Mtc\MercuryDataModels\ApiNotification;
use Mtc\MercuryDataModels\TenantFeature;
use Mtc\MercuryDataModels\Vehicle;

class PhyronController extends Controller
{
    public function index(PhyronStockRequest $request)
    {
        return TenantFeature::query()
            ->where('feature', 'phyron-feed')
            ->whereHas('tenant', fn($query) => $query->whereNull('suspended_at'))
            ->get()
            ->map(fn(TenantFeature $feature) => [
                'site' => $feature->tenant_id,
                'stock_endpoint' => route('phyron.stock', $feature->tenant_id),
                'vdp_endpoint' => route('phyron.vdp', $feature->tenant_id),
            ]);
    }

    public function store(PhyronNotificationRequest $request): Response
    {
        tenancy()->initialize($request->tenant());
        $notification = ApiNotification::query()
            ->create([
                'provider' => 'phyron',
                'data' => $request->input(),
                'headers' => $request->header(),
                'data_model' => 'vehicle',
                'reference' => $request->input('vehicleId'),
            ]);

        if ($request->has('images')) {
            $this->dispatch(
                new ImportImageListNotificationJob(
                    $request->vehicle(),
                    $request->input('images'),
                    $notification,
                    'phyron',
                )
            );
        }

        if ($request->vehicle()) {
            if ($request->has('video')) {
                $request->vehicle()->update(['main_video_url' => $request->input('video')]);
            }

            $notification->update([
                'processed' => true
            ]);
        }

        return response([
            'status' => 'received'
        ]);
    }

    public function stock(Request $request): Response
    {
        if ($request->input('api_token') != config('auth.api_auth_token')) {
            abort(403);
        }
        return response(Vehicle::query()
            ->with([
                'dealership',
                'make',
                'model',
            ])
            ->withImageCount()
            ->when(
                Settings::get('image-sync-exclude-sold'),
                fn($query) => $query->where('is_sold', '!=', 1)
            )
            ->when(
                Settings::get('image-sync-exclude-reserved'),
                fn($query) => $query->where('is_reserved', '!=', 1)
            )
            ->exportable()
            ->get()
            ->map(function (Vehicle $vehicle) {
                $condition = $vehicle->is_new ? 'New' : 'Used';
                if ($vehicle->is_demo) {
                    $condition = 'CPO';
                }
                return [
                    'dealer_id' => $vehicle->dealership?->data['phyron-dealer-id'] ?? '',
                    'vehicle_id' => $vehicle->uuid,
                    'full_registration' => $vehicle->vrm_condensed,
                    'make' => $vehicle->make?->name,
                    'model' => $vehicle->model?->name,
                    'variant' => $vehicle->derivative,
                    'image_count' => $vehicle->image_count,
                    'street_address' => $vehicle->dealership?->address1,
                    'city' => $vehicle->dealership?->city,
                    'postcode' => $vehicle->dealership?->postcode,
                    'country' => $vehicle->dealership?->country,
                    'latitude' => $vehicle->dealership?->lat,
                    'longitude' => $vehicle->dealership?->lng,
                    'landing_page_url' => Site::vehicleUrl($vehicle),
                    'vehicle_condition' => $condition,
                ];
            }));
    }

    public function vdp(Request $request): Response
    {
        if ($request->input('api_token') != config('auth.api_auth_token')) {
            abort(403);
        }
        return response(Vehicle::query()
            ->with([
                'mediaUses.media',
                'dealership',
                'make',
                'model',
                'transmission',
                'fuelType',
                'bodyStyle',
                'drivetrain',
                'features',
                'specs',
                'equipment',
            ])
            ->when(
                Settings::get('image-sync-exclude-sold'),
                fn($query) => $query->where('is_sold', '!=', 1)
            )
            ->when(
                Settings::get('image-sync-exclude-reserved'),
                fn($query) => $query->where('is_reserved', '!=', 1)
            )
            ->exportable()
            ->get()
            ->map(function (Vehicle $vehicle) {
                return [
                    'dealer_ID' => $vehicle->dealership?->data['phyron-dealer-id'] ?? '',
                    'Vehicle_ID' => $vehicle->uuid,
                    'FullRegistration' => str_replace(' ', '', $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,
                    'FourWheelDrive' => $vehicle->drivetrain?->name == 'Four Wheel Drive' ? 'Y' : 'N',
                    'Images' => $vehicle->mediaUses
                        ->filter(fn(MediaUse $use) => $use->media)
                        ->map(fn(MediaUse $mediaUse) => $mediaUse->getUrl('large')),
                    'Options' => $vehicle->specs->count()
                        ? $vehicle->specs->pluck('description')
                        : ($vehicle->features->count()
                            ? $vehicle->features->pluck('name')
                            : $vehicle->equipment->pluck('description')),
                ];
            }));
    }
}
