<?php

namespace App\Modules\Payroll\Models;

use App\Models\User;
use App\Modules\Admin\Tenancy\Traits\BelongsToTenant;
use App\Modules\Payroll\Support\PayrollPeriodStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class PayrollPeriod extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'tenant_id',
        'name',
        'start_date',
        'end_date',
        'status',
        'processed_at',
        'finalized_at',
        'created_by',
        'finalized_by',
    ];

    protected function casts(): array
    {
        return [
            'start_date' => 'date',
            'end_date' => 'date',
            'processed_at' => 'datetime',
            'finalized_at' => 'datetime',
        ];
    }

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

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

    public function snapshots(): HasMany
    {
        return $this->hasMany(PayrollEmployeeSnapshot::class, 'payroll_period_id');
    }

    public function adjustments(): HasMany
    {
        return $this->hasMany(PayrollAdjustment::class, 'payroll_period_id');
    }

    public function isFinalized(): bool
    {
        return $this->status === PayrollPeriodStatus::FINALIZED;
    }

    public function isLocked(): bool
    {
        return $this->isFinalized();
    }
}
