<?php

namespace App\Domain\HR\Models;

use App\Domain\HR\Enums\PayslipItemType;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use App\Domain\Shared\Traits\ScopedThroughBranch;

class PayslipItem extends Model
{
    use ScopedThroughBranch;

    /**
     * The parent whose branch this row inherits. A line item has no
     * branch of its own and must not grow one — a denormalised copy
     * here is a second source of truth that drifts the first time the
     * parent moves.
     */
    protected static string $branchScopeRelation = 'payslip';

    protected $fillable = [
        'payslip_id',
        'type',
        'description',
        'quantity',
        'rate',
        'amount',
        'is_deduction',
        'source_type',
        'source_id',
        'metadata',
        'sort_order',
    ];

    protected $casts = [
        'type' => PayslipItemType::class,
        'quantity' => 'decimal:2',
        'rate' => 'integer',
        'amount' => 'integer',
        'is_deduction' => 'boolean',
        'metadata' => 'array',
        'sort_order' => 'integer',
    ];

    // --- Relationships ---

    public function payslip(): BelongsTo
    {
        return $this->belongsTo(Payslip::class);
    }

    public function source(): MorphTo
    {
        return $this->morphTo('source', 'source_type', 'source_id');
    }
}
