<?php

namespace App\Console\Commands;

use App\Facades\Settings;
use App\Modules\ImageSync\AutoImaging;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Mtc\ContentManager\Facades\Media;
use Mtc\MercuryDataModels\ApiNotification;
use Mtc\MercuryDataModels\Country;
use Mtc\MercuryDataModels\Vehicle;

class RetryAutoImagingNotifications extends Command
{
    use DispatchesJobs;

    private array $vehicles = [];

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'retry:auto-imaging';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Retry processing AutoImaging notifications';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $notifications = ApiNotification::query()
            ->where('provider', 'auto-imaging')
            ->get();

        $this->output->info('Total notifications: ' . $notifications->count());

        $notifications
            ->filter(fn ($notification) => $this->canProcessImages($notification))
            ->filter(fn ($notification) => !empty($notification['data']['media']))
            ->tap(fn ($total) => $this->output->info('Image notifications to process: ' . $total->count()))
            ->each(fn ($notification) => Media::setUsesForModel(
                $notification['data']['media'],
                $this->getVehicle($notification),
                ['primary' => true]
            ));

        $videoCount = 0;
        $notifications->each(function ($notification) use (&$videoCount) {
            $vehicle = $this->getVehicle($notification);
            if ($vehicle && AutoImaging::applyVideoUrls($vehicle, $notification->data ?? [])) {
                $videoCount++;
            }
        });
        $this->output->info('Video notifications updated: ' . $videoCount);
    }

    private function canProcessImages($notification): bool
    {
        $vehicle = $this->getVehicle($notification);
        return $vehicle && $vehicle->mediaUses()->count() === 0;
    }

    private function getVehicle($notification): ?Vehicle
    {
        if (!isset($this->vehicles[$notification->reference])) {
            $country = Settings::get('app-details-country') ?? config('app.default_country');
            $this->vehicles[$notification->reference] = Vehicle::query()
                ->where('registration_number', Country::normalizeNumberPlate($country, $notification->reference))
                ->orWhere('vin', $notification->reference)
                ->first();
        }

        return $this->vehicles[$notification->reference] ?? null;
    }
}
