<?php

namespace App\Services\Geolocation;

use App\Facades\Feature;
use App\Services\Geolocation\Contracts\GeolocationResolver;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\Country;
use Mtc\MercuryDataModels\Currency;

class CurrencyDetector
{
    public function __construct(
        private readonly GeolocationResolver $resolver,
        private readonly ClientIpExtractor $ipExtractor
    ) {
    }

    public function detect(Request $request): ?string
    {
        if (!Feature::isEnabled('multi-currency')) {
            return null;
        }

        $ip = $this->ipExtractor->fromRequest($request);
        if ($ip === null) {
            return null;
        }

        $countryCode = $this->resolver->countryCodeForIp($ip);
        if ($countryCode === null) {
            return null;
        }

        return $this->currencyForCountry($countryCode);
    }

    private function currencyForCountry(string $countryCode): ?string
    {
        $currencyCode = Country::query()
            ->where('code', $countryCode)
            ->whereNotNull('currency_code')
            ->value('currency_code');

        if (!is_string($currencyCode) || $currencyCode === '') {
            return null;
        }

        $supported = Currency::query()->where('code', $currencyCode)->exists();
        return $supported ? $currencyCode : null;
    }
}
