<?php

namespace App\Modules\Payroll\Requests;

use App\Modules\Payroll\Models\PayrollPeriod;
use App\Modules\Payroll\Repositories\PayrollPeriodRepository;
use App\Modules\Payroll\Support\PayrollAdjustmentType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StorePayrollAdjustmentRequest extends FormRequest
{
    public function authorize(): bool
    {
        $user = $this->user();
        if ($user === null || ! $user->can('payroll.adjustments.manage')) {
            return false;
        }
        $id = (int) $this->route('period');
        if ($id < 1) {
            return false;
        }
        $period = app(PayrollPeriodRepository::class)->findForTenant((int) $user->tenant_id, $id);

        return $period instanceof PayrollPeriod && $user->can('manageAdjustments', $period);
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $tid = (int) $this->user()->tenant_id;

        return [
            'employee_id' => [
                'required',
                'integer',
                Rule::exists('employees', 'id')->where(fn ($q) => $q->where('tenant_id', $tid)),
            ],
            'type' => ['required', 'string', Rule::in(PayrollAdjustmentType::all())],
            'amount' => ['required', 'numeric', 'min:0.01'],
            'reason' => ['required', 'string', 'max:5000'],
        ];
    }
}
