<?php

namespace Modules\Employee\Http\Requests\Employee;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Modules\Core\Enums\StatusEnum;
use Modules\Core\Traits\FailedValidation;

class StoreEmployeeRequest extends FormRequest
{
    use FailedValidation;
    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        $createLogin = $this->boolean('createLogin');

        $emailRules = [
            $createLogin ? 'required' : 'nullable',
            'email',
            'max:255',
            'unique:employees,email',
        ];

        $phoneRules = [
            'required',
            'string',
            'max:20',
            'unique:employees,phone',
        ];

        if ($createLogin) {
            $emailRules[] = Rule::unique('users', 'email');
            $phoneRules[] = Rule::unique('users', 'phone');
        }

        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => $emailRules,
            'phone' => $phoneRules,
            'emp_number' => [
                'nullable',
                'string',
                'max:20',
                'unique:employees,emp_number',
                'regex:/^E\d{6}$/'
            ],
            'createLogin' => ['required', 'boolean'],
            'password' => [
                'nullable',
                'string',
                'min:6',
                Rule::requiredIf($createLogin),
                'confirmed',
            ],
            'password_confirmation' => [
                'nullable',
                'string',
                'min:6',
                Rule::requiredIf($createLogin),
            ],
            'status' => [
                'nullable',
                Rule::requiredIf($createLogin),
                Rule::enum(StatusEnum::class),
            ],
        ];
    }

    public function attributes(): array
    {
        return [
            'emp_number' => 'employee number',
        ];
    }

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