<?php

namespace App\Console\Commands;

use App\Facades\Settings;
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()
            ->tap(fn ($notifications) => $this->output->info('Total notifications: ' . $notifications->count()))
            ->filter(fn ($notification) => $this->shouldProcess($notification));

        $notifications
            ->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]
            ));

        $notifications
            ->filter(fn ($notification) => !empty($notification->data['vimeoUrl']))
            ->tap(fn ($total) => $this->output->info('Video notification to process: ' . $total->count()))
            ->each(fn ($notification) => $this->getVehicle($notification)?->update([
                'main_video_url' => $notification->data['vimeoUrl']
            ]));
    }

    private function shouldProcess($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;
    }
}
