<?php

namespace App\Domain\Payroll\Models;

use App\Domain\Payroll\Enums\PayrollStatus;
use App\Support\Concerns\HasUuid;
use App\Support\Money\Money;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use RuntimeException;

/** One payroll for a period (§51). */
class PayrollRun extends Model
{
    use HasUuid;

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

    protected function casts(): array
    {
        return [
            'status' => PayrollStatus::class,
            'period_start' => 'date',
            'period_end' => 'date',
            'pay_date' => 'date',
            'gross_earnings' => 'integer',
            'total_deductions' => 'integer',
            'employer_contributions' => 'integer',
            'net_payable' => 'integer',
            'employee_count' => 'integer',
            'calculated_at' => 'datetime',
            'approved_at' => 'datetime',
            'posted_at' => 'datetime',
            'paid_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::deleting(function (self $run) {
            if ($run->status !== PayrollStatus::Draft && $run->status !== PayrollStatus::Calculated) {
                throw new RuntimeException('A payroll that has been approved cannot be deleted.');
            }
        });
    }

    public function payslips(): HasMany
    {
        return $this->hasMany(Payslip::class);
    }

    public function net(): Money
    {
        return Money::of((int) $this->net_payable, $this->currency);
    }
}
