<?php

namespace App\Modules\HR\Loans\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class LoanRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->route('loan')
            ? ($this->user()?->can('loans.update') ?? false)
            : ($this->user()?->can('loans.create') ?? false);
    }

    public function rules(): array
    {
        $tenant = $this->user()?->tenant_id;

        return [
            'employee_id' => ['required', Rule::exists('employees', 'id')->where(fn ($q) => $q->where('tenant_id', $tenant))],
            'type' => ['required', Rule::in(['loan', 'advance'])],
            'amount' => ['required', 'numeric', 'gt:0'],
            'interest_rate' => ['nullable', 'numeric', 'min:0'],
            'installment_count' => ['required', 'integer', 'min:1', 'max:120'],
            'start_date' => ['required', 'date'],
            'reason' => ['nullable', 'string', 'max:5000'],
            'notes' => ['nullable', 'string', 'max:5000'],
        ];
    }
}
