<?php

namespace Daylight\Core\Models;

use Daylight\Core\Models\Shipping\ShippingZone;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use PeterColes\Countries\CountriesFacade;

class Country extends Model
{
    protected $guarded = [];

    public function taxRates(): HasMany
    {
        return $this->hasMany(TaxRate::class);
    }

    public function name(): Attribute
    {
        return Attribute::make(
            get: fn () => CountriesFacade::countryName($this->code, app()->getLocale())
        );
    }

    public function shippingZones(): BelongsToMany
    {
        return $this->belongsToMany(ShippingZone::class)
            ->orderBy('priority');
    }

    public function defaultTaxRate(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->getTaxRate()
        );
    }

    public function getTaxRate($type = 'default')
    {
        return $this->taxRates->where('type', $type)->first()?->rate ?? 0;
    }
}
