<?php

namespace Daylight\Core\Models;

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(daylightModel('tax_rate'));
    }

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

    public function shippingZones(): BelongsToMany
    {
        return $this->belongsToMany(daylightModel('shipping_zone'))
            ->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;
    }
}
