<?php

namespace App\Domain\Financial\Models;

use App\Domain\Participant\Models\Participant;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\BelongsToBranch;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * One operator's decision about one participant's account, and everything it
 * did.
 *
 * Treated as immutable, like transactions and audit_logs: a settlement that was
 * wrong is answered with another settlement, never with an edit. Nothing in the
 * application updates a row after SettlementService writes it.
 */
class Settlement extends Model
{
    use HasUuid, BelongsToAcademy, BelongsToBranch;

    protected $fillable = [
        'academy_id',
        'branch_id',
        'participant_id',
        'reference',
        'reason',
        'actions',
        'collected_amount',
        'waived_amount',
        'billed_amount',
        'applied_by',
        'applied_at',
    ];

    protected function casts(): array
    {
        return [
            'actions' => 'array',
            'collected_amount' => 'integer',
            'waived_amount' => 'integer',
            'billed_amount' => 'integer',
            'applied_at' => 'datetime',
        ];
    }

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

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

    /** Net effect on the ledger: what came in, less what was given up. */
    public function netCollected(): int
    {
        return $this->collected_amount;
    }
}
