<?php

namespace Daylight\Core\Models;

use App\Models\User;
use Daylight\Core\Models\Enums\AddressType;
use Daylight\Core\Models\Enums\CustomerType;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class Customer extends Model
{
    use HasFactory;

    protected $guarded = [];

    protected $casts = [
        'type' => CustomerType::class,
    ];

    public function customerGroups(): BelongsToMany
    {
        return $this->belongsToMany(CustomerGroup::class)->withTimestamps();
    }

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

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

    public function defaultBillingAddress(): HasOne
    {
        return $this->addresses()->one()->ofMany([
            'id' => 'max',
        ], function (Builder $builder) {
            $builder
                ->whereDefault(1)
                ->whereType(AddressType::BILLING);
        });
    }

    public function shippingAddresses(): HasMany
    {
        return $this->addresses()->whereType(AddressType::SHIPPING);
    }

    public function billingAddresses(): HasMany
    {
        return $this->addresses()->whereType(AddressType::BILLING);
    }

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

    public function getVatRates()
    {
        $this->loadMissing('defaultBillingAddress.country.taxRates');

        return $this->defaultBillingAddress->country->taxRates;
    }
}
