<?php

namespace App\Jobs;

use App\Imports\AutoTraderApiToVehicleImport;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\ApiNotification;
use Mtc\MercuryDataModels\Media;
use Mtc\MercuryDataModels\SalesChannelHistory;
use Mtc\MercuryDataModels\Vehicle;

class HandleAutoTraderHubNotification implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    protected AutoTraderApiToVehicleImport $import;

    /**
     * Create a new job instance.
     */
    public function __construct(
        private readonly array $input,
        private ApiNotification $apiNotification
    ) {
        $this->import = resolve(AutoTraderApiToVehicleImport::class);
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $action = $this->input['type'] ?? null;

        match ($action) {
            'stock-upsert' => $this->handleStockUpsert(),
            'STOCK_UPDATE' => $this->handleStockUpdate(),
            default => $this->handleUnrecognizedAction($action),
        };
    }

    private function handleStockUpsert(): void
    {
        if ($this->input['result'] === 'success') {
            $this->setAutoTraderIdForVehicle();
            $this->handleStockUpdate(false);
        }

        SalesChannelHistory::query()
            ->create([
                'channel' => 'auto-trader',
                'vehicle_id' => $this->input['vehicle_id'],
                'was_successful' => $this->input['result'] === 'success',
                'details' => json_encode($this->input['data']),
            ]);
    }

    private function setAutoTraderIdForVehicle(): void
    {
        Vehicle::query()
            ->where('id', $this->input['vehicle_id'])
            ->whereNull('auto_trader_id')
            ->update([
                'auto_trader_id' => $this->input['stock_id'],
            ]);

        if (isset($this->input['uploaded_images'])) {
            collect($this->input['uploaded_images'])
                ->each(function ($image) {
                    Media::query()
                        ->where('id', $image['media_id'])
                        ->update([
                            'image_provider' => 'auto-trader',
                            'auto_trader_id' => $image['auto_trader_id']
                        ]);
                });
        }
    }

    private function handleStockUpdate($importImages = true): void
    {
        $vehicle_data = $this->input['data'];

        if (!$this->import->exists($vehicle_data)) {
            $this->import->add($vehicle_data, $importImages);
        }

        $this->import->update($vehicle_data, $importImages);

        $this->apiNotification->processed = 1;
        $this->apiNotification->save();
    }

    private function handleUnrecognizedAction($action): void
    {
        Log::warning('AutoTrader Hub notification - unrecognized action', [
            'action' => $action,
            'input' => $this->input,
            'tenant' => tenant('id'),
        ]);
    }
}
