<?php

namespace App\Jobs;

use App\Contracts\LeaseDataProvider;
use App\IntegrationRepository;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Mtc\Notifications\Facades\Notification;

class RunLeaseDataSyncJob implements ShouldQueue, ShouldBeUnique
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public $timeout = 7200;

    public $retryAfter = 1900;

    /**
     * The number of seconds after which the job's unique lock will be released.
     *
     * @var int
     */
    public $uniqueFor = 7200;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(private readonly bool $ignoreSchedule = false)
    {
        $this->onQueue('sync');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        new IntegrationRepository()->getEnabledForType('lease-data')
            ->map(fn($integration) => App::make($integration['class']))
            ->filter(fn($integration) => $integration instanceof LeaseDataProvider)
            ->each(function (LeaseDataProvider $provider) {
                $this->importFromProvider($provider);
            });
    }

    private function importFromProvider(LeaseDataProvider $provider)
    {
        try {
            $start = microtime(true);
            $provider->runScheduledImport();
            $runtime = round(microtime(true) - $start);

            Notification::addNotification(
                'info',
                "Lease data sync process finished. Runtime: {$runtime}s",
                $provider->name(),
                'edit-vehicles',
                "",
            );
        } catch (Exception $exception) {
            $message = '[' . tenant('id') . '] ' . $provider->name()
                . ' lease data sync failed: ' . $exception->getMessage();

            Log::error($message, [
                'message' => $exception->getMessage(),
                'trace' => $exception->getTrace(),
            ]);
        }
    }

    public function uniqueId(): string
    {
        return \app()->environment() === 'production'
            ? tenant('id') ?? 'no-tenant'
            : Str::random(32);
    }
}
