<?php

namespace Daylight\Core\Services;

use Daylight\Core\Models\TaxClass;
use Daylight\Core\Models\TaxRate;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;

class Tax
{
    public static function all(): Collection
    {
        return Cache::rememberForever('tax', function () {
            return TaxClass::query()
                ->with([
                    'taxRates',
                ])
                ->get();
        });
    }

    public static function defaultTaxRateForClass(int $class = 1): ?float
    {
        return static::all()
            ->filter(function (TaxClass $taxClass) use ($class) {
                return $taxClass->id === $class;
            })
            ->map(function (TaxClass $taxClass) {
                return $taxClass->taxRates->filter(function (TaxRate $taxRate) {
                    return $taxRate->country_id === Countries::defaultCountry()->id;
                });
            })
            ->flatten()
            ->first()
            ?->rate;
    }
}
