<?php

namespace Modules\Academic\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreAcademicYearRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return $this->user()->role === 'admin';
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'name' => [
                'required',
                'string',
                'max:255',
                'unique:academic_years,name'
            ],
            'start_date' => [
                'required',
                'date'
            ],
            'end_date' => [
                'required',
                'date',
                'after:start_date'
            ],
            'is_active' => [
                'boolean'
            ],
        ];
    }

    /**
     * Get custom validation messages.
     */
    public function messages(): array
    {
        return [
            'name.required' => 'Please enter the academic year name.',
            'name.unique' => 'An academic year with this name already exists.',
            'start_date.required' => 'Please select the start date.',
            'start_date.after_or_equal' => 'Start date cannot be in the past.',
            'end_date.required' => 'Please select the end date.',
            'end_date.after' => 'End date must be after the start date.',
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            // Check if the date range overlaps with existing academic years
            if ($this->start_date && $this->end_date) {
                $overlapping = \Modules\Academic\Models\AcademicYear::where(function ($query) {
                    $query->whereBetween('start_date', [$this->start_date, $this->end_date])
                          ->orWhereBetween('end_date', [$this->start_date, $this->end_date])
                          ->orWhere(function ($q) {
                              $q->where('start_date', '<=', $this->start_date)
                                ->where('end_date', '>=', $this->end_date);
                          });
                })->exists();

                if ($overlapping) {
                    $validator->errors()->add('start_date', 'The date range overlaps with an existing academic year.');
                }
            }

            // Validate academic year duration (should be reasonable)
            if ($this->start_date && $this->end_date) {
                $startDate = \Carbon\Carbon::parse($this->start_date);
                $endDate = \Carbon\Carbon::parse($this->end_date);
                $monthsDiff = $startDate->diffInMonths($endDate);

                if ($monthsDiff < 6) {
                    $validator->errors()->add('end_date', 'Academic year should be at least 6 months long.');
                }

                if ($monthsDiff > 18) {
                    $validator->errors()->add('end_date', 'Academic year should not exceed 18 months.');
                }
            }
        });
    }
}
