<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'name' => 'required|string|max:100',
            'type' => 'required|in:income,expense',
            'account_id' => 'required|exists:accounts,id',
            'category_id' => 'nullable|exists:categories,id',
            'amount' => 'required|numeric|min:0.01',
            'currency_id' => 'nullable|exists:currencies,id',
            'frequency' => 'required|in:daily,weekly,biweekly,monthly,quarterly,yearly',
            'interval' => 'nullable|integer|min:1|max:365',
            'start_date' => 'required|date',
            'end_date' => 'nullable|date|after:start_date',
            'next_due_date' => 'nullable|date',
            'description' => 'nullable|string|max:500',
            'payee' => 'nullable|string|max:200',
            'auto_create' => 'boolean',
            'reminder_days' => 'nullable|integer|min:0|max:30',
        ];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'name.required' => 'Name is required.',
            'type.required' => 'Please select transaction type.',
            'account_id.required' => 'Please select an account.',
            'amount.required' => 'Amount is required.',
            'amount.min' => 'Amount must be greater than zero.',
            'frequency.required' => 'Please select frequency.',
            'start_date.required' => 'Start date is required.',
            'end_date.after' => 'End date must be after start date.',
        ];
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation()
    {
        // Set next_due_date to start_date if not provided
        if (!$this->has('next_due_date') && $this->has('start_date')) {
            $this->merge(['next_due_date' => $this->start_date]);
        }

        // Set default interval if not provided
        if (!$this->has('interval')) {
            $this->merge(['interval' => 1]);
        }
    }
}
