<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class LoanApplicationRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true; // Authorization is handled in controller
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'amount_requested' => 'required|numeric|min:' . ($this->loanProduct->min_amount ?? 0) . '|max:' . ($this->loanProduct->max_amount ?? 999999999),
            'term_months' => 'required|integer|min:' . ($this->loanProduct->min_term_months ?? 1) . '|max:' . ($this->loanProduct->max_term_months ?? 360),
            'purpose' => 'required|string|max:1000',
            'employment_status' => 'nullable|string|in:employed,self_employed,business_owner,retired,other',
            'employer_name' => 'nullable|string|max:191',
            'monthly_income' => 'nullable|numeric|min:0',
            'income_currency' => 'nullable|in:USD,SSP,KES,UGX',
            'documents' => 'nullable|array',
            'documents.*' => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:5120',
        ];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        $product = $this->loanProduct;
        
        return [
            'amount_requested.required' => 'Loan amount is required.',
            'amount_requested.min' => 'Minimum loan amount is ' . number_format($product->min_amount ?? 0, 2) . ' ' . ($product->currency ?? 'USD'),
            'amount_requested.max' => 'Maximum loan amount is ' . number_format($product->max_amount ?? 999999999, 2) . ' ' . ($product->currency ?? 'USD'),
            'term_months.required' => 'Loan term is required.',
            'term_months.min' => 'Minimum term is ' . ($product->min_term_months ?? 1) . ' months.',
            'term_months.max' => 'Maximum term is ' . ($product->max_term_months ?? 360) . ' months.',
            'purpose.required' => 'Please describe the purpose of the loan.',
            'documents.*.mimes' => 'Documents must be PDF, JPG, or PNG files.',
            'documents.*.max' => 'Each document must be under 5MB.',
        ];
    }
}
