<?php

namespace App\Models;

use App\Enums\LeaveRequestStatus;
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\SoftDeletes;

#[Appends(['formatted_end_date', 'formatted_start_date', 'status_label'])]
#[Guarded(['id'])]
class LeaveRequest extends Model
{
    use HasFactory, SoftDeletes;

    protected function casts(): array
    {
        return [
            'status' => LeaveRequestStatus::class,
            'start_date' => 'date:Y-m-d',
            'end_date' => 'date:Y-m-d',
            'total_days' => 'integer',
            'verified_at' => 'datetime',
        ];
    }

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

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

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

    #[Scope]
    protected function approved(Builder $query): void
    {
        $query->where('status', LeaveRequestStatus::APPROVED);
    }

    #[Scope]
    protected function cancelled(Builder $query): void
    {
        $query->where('status', LeaveRequestStatus::CANCELLED);
    }

    #[Scope]
    protected function pending(Builder $query): void
    {
        $query->where('status', LeaveRequestStatus::PENDING);
    }

    #[Scope]
    protected function rejected(Builder $query): void
    {
        $query->where('status', LeaveRequestStatus::REJECTED);
    }

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

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