<?php

namespace App\Domain\Financial\Models;

use App\Domain\Financial\Enums\AllocationType;
use App\Domain\Shared\Traits\HasUuid;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * One destination inside a routing rule: an account and the share it takes.
 *
 * No global academy scope: a line is only ever reached through its mapping,
 * which is scoped, and adding a second scope here would hide lines from the
 * ledger writer whenever it runs outside a request (the queue, a console
 * command) where no current academy is bound. `academy_id` is still stamped —
 * it is a tenant table and every query that goes near it must be able to say so.
 */
class RevenueMappingLine extends Model
{
    use HasUuid;

    protected $fillable = [
        'academy_id',
        'revenue_mapping_id',
        'account_id',
        'allocation_type',
        'percentage_bp',
        'fixed_amount',
        'label',
        'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'allocation_type' => AllocationType::class,
            'percentage_bp' => 'integer',
            'fixed_amount' => 'integer',
            'sort_order' => 'integer',
        ];
    }

    public function mapping(): BelongsTo
    {
        return $this->belongsTo(RevenueMapping::class, 'revenue_mapping_id');
    }

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

    /** The share as a percentage, for display only. */
    public function percent(): float
    {
        return ($this->percentage_bp ?? 0) / 100;
    }

    /** How this line reads on the rules list: "١٠٪", "٥٫٠٠ ج.م", "الباقي". */
    public function shareLabel(): string
    {
        return match ($this->allocation_type) {
            AllocationType::Percentage => rtrim(rtrim(number_format($this->percent(), 2), '0'), '.') . '%',
            AllocationType::Fixed => format_money((int) $this->fixed_amount),
            AllocationType::Remainder => 'الباقي',
        };
    }
}
