<?php

namespace App\Http\Requests\Admin\Finance;

use App\Enums\EmployeeAdvanceStatus;
use App\Enums\Permission;
use App\Models\EmployeeAdvance;
use Illuminate\Foundation\Http\FormRequest;

class EmployeeAdvanceRequest extends FormRequest
{
    public function authorize(): bool
    {
        $user = $this->user();

        if ($user === null || $user->can(Permission::EMPLOYEE_ADVANCES_VERIFY->value)) {
            return false;
        }

        if ($this->isMethod('POST')) {
            return $user->can(Permission::EMPLOYEE_ADVANCES_CREATE->value)
                && $user->employee !== null;
        }

        if (! $user->can(Permission::EMPLOYEE_ADVANCES_UPDATE->value)) {
            return false;
        }

        /** @var EmployeeAdvance|null $employeeAdvance */
        $employeeAdvance = $this->route('employeeAdvance');

        return $employeeAdvance?->status === EmployeeAdvanceStatus::PENDING
            && $user->employee?->id === $employeeAdvance->employee_id;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return [
            'amount' => ['required', 'integer', 'min:1'],
            'description' => ['required', 'string', 'max:100'],
            'due_date' => ['required', 'date', 'after_or_equal:today'],
        ];
    }

    /**
     * @return array<string, string>
     */
    public function attributes(): array
    {
        return [
            'amount' => 'jumlah',
            'description' => 'keterangan',
            'due_date' => 'jatuh tempo',
        ];
    }
}
