<?php

namespace App\Http\Requests\Admin\Users\Student;

use App\Enums\Gender;
use App\Enums\StudentStatus;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StudentRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can($this->isMethod('post') ? 'create-students' : 'update-students');
    }

    public function rules(): array
    {
        $userId = $this->route('user')?->id;

        return [
            'username' => [
                'required',
                'string',
                'max:20',
                'min:5',
                'alpha_dash',
                $userId === null
                    ? Rule::unique('users')
                    : Rule::unique('users')->ignore($userId),
            ],
            'email' => [
                'required',
                'string',
                'email',
                'max:255',
                $userId === null
                    ? Rule::unique('users')
                    : Rule::unique('users')->ignore($userId),
            ],

            // Profile
            'full_name' => ['required', 'string', 'max:150'],
            'phone_number' => ['required', 'string', 'max:20'],
            'address' => ['required', 'string'],
            'gender' => ['required', 'string', Rule::enum(Gender::class)],
            'birth_date' => ['required', 'date'],
            'birth_place' => ['required', 'string', 'max:100'],

            // Student fields
            'student_number' => [
                'required',
                'string',
                'max:10',
                Rule::unique('students')->ignore($userId, 'user_id'),
            ],
            'department_id' => [
                'required',
                'integer',
                Rule::exists('departments', 'id'),
            ],
            'enrollment_year' => [
                'required',
                'integer',
                'digits:4',
            ],
            'current_semester' => [
                'required',
                'integer',
                'min:1',
                'max:14',
            ],
            'academic_advisor_id' => [
                'required',
                'integer',
                Rule::exists('lecturer_department', 'lecturer_id')
                    ->where('department_id', $this->input('department_id')),
            ],
            'status' => [
                'nullable',
                'string',
                Rule::enum(StudentStatus::class),
            ],
        ];
    }
}
