<?php

namespace App\Domain\Financial\Models;

use App\Domain\Financial\Enums\RevenueSource;
use App\Domain\Financial\Enums\TaxMode;
use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;

/**
 * One routing rule: where the money from a revenue source goes, and what tax
 * comes off it first.
 *
 * A rule with no scope is the academy's default for that source. A rule with a
 * scope narrows it to one product, programme or event, and beats the default.
 * That two-level fallback is the same shape Odoo gives a product versus its
 * category and Dynamics gives an item versus its posting group — specific wins,
 * and there is always a general answer underneath so nothing is ever unrouted.
 */
class RevenueMapping extends Model
{
    use HasUuid, BelongsToAcademy, Auditable;

    protected $fillable = [
        'academy_id',
        'source_key',
        'scope_type',
        'scope_id',
        'label',
        'is_active',
        'tax_mode',
        'tax_rate_bp',
        'tax_account_id',
        'notes',
        'updated_by',
    ];

    protected function casts(): array
    {
        return [
            'source_key' => RevenueSource::class,
            'is_active' => 'boolean',
            'tax_mode' => TaxMode::class,
            'tax_rate_bp' => 'integer',
            'scope_id' => 'integer',
        ];
    }

    public function lines(): HasMany
    {
        return $this->hasMany(RevenueMappingLine::class)->orderBy('sort_order')->orderBy('id');
    }

    public function taxAccount(): BelongsTo
    {
        return $this->belongsTo(FinancialAccount::class, 'tax_account_id');
    }

    public function scope(): MorphTo
    {
        return $this->morphTo(__FUNCTION__, 'scope_type', 'scope_id');
    }

    public function updatedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    public function isDefault(): bool
    {
        return $this->scope_type === null;
    }

    /** The tax rate as a percentage, for display only. */
    public function taxRatePercent(): float
    {
        return $this->tax_rate_bp / 100;
    }

    /**
     * Changing where money lands is a financial act and belongs in the audit
     * log beside the invoice corrections and the settlements.
     */
    public function isFinancialAudit(): bool
    {
        return true;
    }
}
