<?php

namespace App\Http\Requests\INSURANCE;

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

class InsurancePolicyRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        
        // **Use the camel‑case route key** exactly as you've declared it:
        $param = $this->route('insurancePolicy');

        $policyId = $param instanceof InsurancePolicy
            ? $param->getKey()
            : $param; // if someone passed an integer instead of bound model


        return [
            'policy_number' => [
                'required',
                'string',
                // tells Laravel: “make sure policy_number is unique, but ignore record #$policyId”
                Rule::unique('insurance_policies', 'policy_number')
                    ->ignore($policyId),
            ],

            'insurer_id'             => ['required', 'exists:insurers,id'],
            'commission_default_id'  => ['required', 'exists:commission_defaults,id'],
            'commission_pct'         => ['sometimes', 'numeric', 'min:0'],
            'custom_name'           => ['sometimes', 'string', 'max:255'],
            'expected_commission'    => ['sometimes', 'numeric', 'min:0'],
            'insured_amount'         => ['required', 'numeric', 'min:0'],
            'premium'                => ['required', 'numeric', 'min:0'],
            'start_date'             => ['required', 'date'],
            'end_date'               => ['required', 'date', 'after_or_equal:start_date'],
            'status'                 => ['required', 'string', Rule::in(['active', 'inactive', 'expired'])],
        ];
    }

    public function messages(): array
    {
        return [
            'policy_number.required'     => '- obavezno polje.',
            'policy_number.unique'       => 'That policy number is already taken.',
            'insurer_id.required'        => 'Molimo vas da izaberete osiguravača.',
            'insurer_id.exists'          => 'Invalid insurer selected.',
            'insured_amount.required'    => '- obavezno polje.',
            'premium.required'           => '- obavezno polje.',
            'commission_default_id.required' => 'Molimo vas da izaberete vrstu osiguranja.',
            'commission_default_id.exists'  => 'Invalid insurance type.',
            'start_date.required'        => '- obavezno polje.',
            'end_date.required'          => 'Kraj osiguranja - obavezno polje.',
            'end_date.after_or_equal'    => 'Mora biti posle početka osiguranja.',
        ];
    }
}
