<?php

namespace App\Http\Resources\VehicleAction;

use App\Facades\Settings;
use Mtc\MercuryDataModels\Vehicle;

class RiskBasedFinanceEligibilityFactory
{
    public function get(Vehicle $vehicle): bool
    {
        if (
            !$vehicle->dealership?->data
            || !array_key_exists('finance-risk-based-pricing', $vehicle->dealership?->data)
        ) {
            return false;
        }

        if (Settings::get('finance-ivendi-enabled') && Settings::get('vehicle-finance-type') === 'peter-vardy') {
            return $this->getPeterVardyEligibility($vehicle);
        }

        return (bool) $vehicle->dealership?->data['finance-risk-based-pricing'];
    }

    private function getPeterVardyEligibility(Vehicle $vehicle): bool
    {
        return $vehicle->dealership->data['finance-risk-based-pricing']
            && $this->financeOptionAllowed($vehicle->getCustom('finance_option'))
            && strtoupper((string) $vehicle->fuelType?->name) !== 'ELECTRIC';
    }

    private function financeOptionAllowed(?int $financeOption): bool
    {
        return in_array(
            $financeOption,
            explode(',', (string) Settings::get('finance-risk-based-pricing-finance-options', ''))
        );
    }
}
