<?php

namespace Mtc\Modules\B2B\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Builder;

class TradeTier extends Model
{
    protected $table = 'b2b_trade_tiers';

    protected $fillable = [
        'name',
        'discount_percentage',
    ];

    protected $casts = [
        'discount_percentage' => 'decimal:2',
    ];

    public function customers(): HasMany
    {
        return $this->hasMany(TradeCustomer::class, 'tier_id');
    }

    public function scopeOrdered(Builder $query): Builder
    {
        return $query->orderBy('discount_percentage')->orderBy('name');
    }

    protected static function booted(): void
    {
        static::deleting(function (TradeTier $tier) {
            if ($tier->customers()->exists()) {
                throw new \RuntimeException('Cannot delete a tier with assigned customers.');
            }
        });
    }
}
