<?php

namespace App\Http\Requests;

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

/**
 * Store Invoice Request
 * Validates invoice creation with comprehensive security checks
 */
class StoreInvoiceRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return $this->user()->can('create', \App\Models\Invoice::class);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'invoice_number' => [
                'nullable',
                'string',
                'max:100',
                'regex:/^[A-Z0-9\-_]+$/i', // Only alphanumeric, hyphens, underscores
                Rule::unique('invoices', 'invoice_number'),
            ],
            'customer_id' => [
                'required',
                'integer',
                Rule::exists('customers', 'id'),
            ],
            'issue_date' => [
                'required',
                'date',
                'before_or_equal:today',
            ],
            'due_date' => [
                'required',
                'date',
                'after_or_equal:issue_date',
            ],
            'status' => [
                'nullable',
                'string',
                Rule::in(['draft', 'sent', 'viewed', 'partial', 'paid', 'overdue', 'cancelled']),
            ],
            'currency' => [
                'nullable',
                'string',
                'size:3',
                'regex:/^[A-Z]{3}$/', // ISO 4217 currency code format
                Rule::exists('currencies', 'code'),
            ],
            'exchange_rate' => [
                'nullable',
                'numeric',
                'min:0',
                'max:999999.999999',
            ],
            'notes' => [
                'nullable',
                'string',
                'max:5000',
            ],
            'terms' => [
                'nullable',
                'string',
                'max:5000',
            ],
            'discount_amount' => [
                'nullable',
                'numeric',
                'min:0',
                'max:999999999.99',
            ],
            'discount_type' => [
                'nullable',
                'string',
                Rule::in(['fixed', 'percentage']),
            ],
            'paid_amount' => [
                'nullable',
                'numeric',
                'min:0',
                'max:999999999.99',
            ],
            'payment_method' => [
                'nullable',
                'string',
                'max:255',
            ],
            'signature_id' => [
                'nullable',
                'integer',
                Rule::exists('signatures', 'id'),
            ],
            'items' => [
                'required',
                'array',
                'min:1',
                'max:1000', // Prevent excessive items
            ],
            'items.*.description' => [
                'required',
                'string',
                'max:1000',
            ],
            'items.*.quantity' => [
                'required',
                'numeric',
                'min:0.01',
                'max:999999.99',
            ],
            'items.*.unit_price' => [
                'required',
                'numeric',
                'min:0',
                'max:999999999.99',
            ],
            'items.*.tax_rate' => [
                'nullable',
                'numeric',
                'min:0',
                'max:100',
            ],
            'items.*.notes' => [
                'nullable',
                'string',
                'max:1000',
            ],
        ];
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'invoice_number.regex' => 'Invoice number can only contain letters, numbers, hyphens, and underscores.',
            'customer_id.required' => 'Please select a customer.',
            'customer_id.exists' => 'Selected customer does not exist.',
            'items.required' => 'At least one item is required.',
            'items.max' => 'Maximum 1000 items allowed per invoice.',
            'items.*.quantity.min' => 'Quantity must be at least 0.01.',
            'items.*.unit_price.min' => 'Unit price must be at least 0.',
        ];
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        // Sanitize string inputs
        if ($this->has('notes')) {
            $this->merge([
                'notes' => strip_tags($this->notes),
            ]);
        }

        if ($this->has('terms')) {
            $this->merge([
                'terms' => strip_tags($this->terms),
            ]);
        }

        // Ensure numeric values are within bounds
        if ($this->has('discount_amount')) {
            $this->merge([
                'discount_amount' => min(max((float) $this->discount_amount, 0), 999999999.99),
            ]);
        }

        if ($this->has('paid_amount')) {
            $this->merge([
                'paid_amount' => min(max((float) $this->paid_amount, 0), 999999999.99),
            ]);
        }
    }
}
