<?php

namespace App\Http\Requests\Admin\Users;

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

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

    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::in(Gender::values())],
            'birth_date' => ['required', 'date'],
            'birth_place' => ['required', 'string', 'max:100'],

            // Lecturer fields
            'lecturer_number' => [
                'required',
                'string',
                'max:20',
                Rule::unique('lecturers')->ignore($userId, 'user_id'),
            ],
            'department_ids' => ['required', 'array', 'min:1'],
            'department_ids.*' => ['integer', Rule::exists('departments', 'id')],
        ];
    }
}
