<?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\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->setAutoTraderIdForVehicle(),
            'STOCK_UPDATE' => $this->handleStockUpdate(),
            default => $this->handleUnrecognizedAction($action),
        };
    }

    private function setAutoTraderIdForVehicle(): void
    {
        if ($this->input['result'] === 'success') {
            Vehicle::query()
                ->where('id', $this->input['vehicle_id'])
                ->whereNull('auto_trader_id')
                ->update([
                    'auto_trader_id' => $this->input['stock_id'],
                ]);
        }
        SalesChannelHistory::query()
            ->create([
                'channel' => 'auto-trader',
                'vehicle_id' => $this->input['vehicle_id'],
                'was_successful' => $this->input['result'] === 'success',
                'details' => $this->input['data'],
            ]);
    }

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

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

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

        $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'),
        ]);
    }
}
