<?php

namespace Modules\Vrc\Services\Adapters\Erp;

use App\TaxRate;
use Modules\Vrc\Services\Contracts\TaxServiceContract;

/**
 * ERP adapter: resolves tax percentages from App\TaxRate. The ERP keeps a
 * group tax's `amount` as the already-summed percentage of its sub-taxes
 * (maintained by TaxUtil), so a single `amount` read is correct for both
 * single and group rates. Scoped by business_id; cached per request.
 */
class ErpTaxService implements TaxServiceContract
{
    /** @var array<string,float> */
    protected array $cache = [];

    public function percentageFor(int $businessId, ?int $taxRateId): float
    {
        if (empty($taxRateId)) {
            return 0.0;
        }

        $key = $businessId . ':' . $taxRateId;
        if (array_key_exists($key, $this->cache)) {
            return $this->cache[$key];
        }

        $rate = TaxRate::where('business_id', $businessId)->find($taxRateId);

        return $this->cache[$key] = $rate ? (float) $rate->amount : 0.0;
    }
}
