<?php

namespace App\Domain\Payroll\Models;

use App\Domain\HR\Models\Employee;
use App\Support\Concerns\HasUuid;
use App\Support\Money\Money;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * What an employee is paid, from a date (§52).
 *
 * A rise supersedes the old structure rather than editing it, so a payslip
 * from before the rise still shows what was paid then.
 */
class EmployeeSalaryStructure extends Model
{
    use HasUuid;

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

    protected function casts(): array
    {
        return [
            'basic_salary' => 'integer',
            'effective_from' => 'date',
            'effective_to' => 'date',
        ];
    }

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

    public function lines(): HasMany
    {
        return $this->hasMany(EmployeeSalaryLine::class, 'employee_salary_structure_id');
    }

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

    /** The structure in force on a date. */
    public function scopeEffectiveOn(Builder $query, string $date): Builder
    {
        return $query->whereDate('effective_from', '<=', $date)
            ->where(fn (Builder $inner) => $inner
                ->whereNull('effective_to')
                ->orWhereDate('effective_to', '>=', $date));
    }
}
