<?php

namespace App\Checklist;

use App\Contracts\GoLiveChecklist;
use App\VehicleSpec\Services\Cap;
use App\VehicleSpec\VehicleSpecServiceHelper;
use Illuminate\Support\Facades\App;
use Mtc\MercuryDataModels\Tenant;
use Mtc\MercuryDataModels\Vehicle;

class SpecsProviderOk extends GoLiveChecklist
{
    public function category(): string
    {
        return GoLiveChecklist::DEVELOPER;
    }

    #[\Override]
    public function isApplicable(Tenant $site): bool
    {
        return !empty(VehicleSpecServiceHelper::initializeForSite());
    }

    public function key(): string
    {
        return 'specs_provider_ok';
    }

    public function handle(): bool
    {
        $vehicle = Vehicle::query()->active()->inRandomOrder()->first();
        if (!$vehicle) {
            $this->failure_reason = __('go-live.errors.no-stock-on-site');
        }

        if (VehicleSpecServiceHelper::determineProvider() === Cap::class) {
            if (!$this->runCapIdLookup($vehicle)) {
                return false;
            }
        }

        $specService = (VehicleSpecServiceHelper::initializeForSite())->getSpec($vehicle);
        return isset($specService->standard_equipment) && $specService->standard_equipment->isNotEmpty();
    }

    private function runCapIdLookup(Vehicle $vehicle): bool
    {
        $cap_data = App::make(Cap::class)->capIdLookup($vehicle);
        if (empty($cap_data)) {
            $this->failure_reason = __('go-live.errors.failed-to-retrieve-cap-id');
            return false;
        }
        if (empty($vehicle->cap_id)) {
            $vehicle->cap_id = $cap_data['cap_id'];
        }
        return true;
    }
}
