<?php

namespace App\Models;

use App\Enums\PayrollPeriodStatus;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

#[Appends(['formatted_closed_at', 'month_name', 'status_label'])]
#[Guarded(['id'])]
class PayrollPeriod extends Model
{
    use HasFactory, SoftDeletes;

    protected function casts(): array
    {
        return [
            'status' => PayrollPeriodStatus::class,
            'year' => 'integer',
            'month' => 'integer',
            'closed_at' => 'datetime',
        ];
    }

    protected function formattedClosedAt(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->closed_at?->translatedFormat('l, d F Y H:i'),
        );
    }

    protected function monthName(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->month ? Carbon::create()->month($this->month)->translatedFormat('F') : null,
        );
    }

    protected function statusLabel(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->status->label(),
        );
    }

    #[Scope]
    protected function closed(Builder $query): void
    {
        $query->where('status', PayrollPeriodStatus::CLOSED);
    }

    #[Scope]
    protected function open(Builder $query): void
    {
        $query->where('status', PayrollPeriodStatus::OPEN);
    }

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

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