<?php

namespace App\Actions\IntegrationVerification;

use App\Modules\Stock\Pinewood;
use Mtc\MercuryDataModels\Dealership;

class VerifyPinewood
{
    public function __construct(private readonly Pinewood $provider)
    {
        //
    }

    public function verify()
    {
        if ($this->hasLocationIdsSet() === false) {
            return response([
                'message' => __('integrations.dealer_id_missing', ['dealer' => 'Pinewood']),
            ], 422);
        }

        if ($this->ableToRetrieveVehicles() === false) {
            return response([
                'message' => __('integrations.unable_to_connect', ['dealer' => 'Pinewood']),
            ], 422);
        }

        return true;
    }

    private function hasLocationIdsSet(): bool
    {
        return Dealership::all()
            ->filter(fn (Dealership $dealership) => !empty($dealership->data['pinewood-location-id']))
            ->isNotEmpty();
    }

    private function ableToRetrieveVehicles(): bool
    {
        $location = Dealership::all()
            ->filter(fn (Dealership $dealership) => !empty($dealership->data['pinewood-location-id']))
            ->first()
            ->data['pinewood-location-id'];

        return $this->provider->fetchVehiclesFromLocation($location)->isNotEmpty();
    }
}
