<?php

namespace App\Domain\Payroll\Models;

use App\Domain\Accounting\Models\LedgerAccount;
use App\Domain\Payroll\Enums\CalculationMode;
use App\Domain\Payroll\Enums\ComponentType;
use App\Support\Concerns\HasUuid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

/** One line of a salary structure (§52). */
class SalaryComponent extends Model
{
    use HasUuid, SoftDeletes;

    protected $guarded = ['id', 'uuid'];

    protected function casts(): array
    {
        return [
            'component_type' => ComponentType::class,
            'calculation_mode' => CalculationMode::class,
            'rate_basis_points' => 'integer',
            'is_taxable' => 'boolean',
            'is_active' => 'boolean',
            'sort_order' => 'integer',
        ];
    }

    /** Where the cost lands: a salary expense, say. */
    public function expenseAccount(): BelongsTo
    {
        return $this->belongsTo(LedgerAccount::class, 'ledger_account_id');
    }

    /** Where a deduction is held until it is handed over: tax payable, say. */
    public function payableAccount(): BelongsTo
    {
        return $this->belongsTo(LedgerAccount::class, 'payable_account_id');
    }

    public function rateLabel(): string
    {
        return rtrim(rtrim(number_format($this->rate_basis_points / 100, 2), '0'), '.').'%';
    }

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true)->orderBy('sort_order')->orderBy('id');
    }
}
