<?php

namespace Modules\User\Requests\Api;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Modules\User\Enums\UserRoleEnum;
use Modules\User\Services\UserService;

class LoginRequest extends FormRequest
{
    public function __construct(
        private UserService $userService
    ){}
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules =
            [
                'email'=>
                [
                    'required',
                    'email'
                ],
                'code'=>
                [
                    'required'
                ]
            ];

        if (request('email') && request('code'))
        {
            $code = $this->userService->checkCode([
                'email'=>request('email'),
                'code'=>request('code'),
            ]);
            if (!$code)
            {
                $rules['not_correct_code'] = 'required';
            }
        }

        return $rules;
    }

    public function messages()
    {
        return [
            'not_correct_code.required' => __('web.not_correct_code')
        ];
    }
    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        $attributes= [
            'email'=>__('web.email'),
            'code'=>__('web.code'),
        ];

        return $attributes;
    }

    /**
     * Handle a failed validation attempt.
     *
     * Override the parent method action if the request is for AJAX
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        // Change response attitude if the request done via Ajax requests like API requests

        $errors = (new ValidationException($validator))->errors();
        $message = $validator->errors()->first();
        throw new HttpResponseException(response()->json(['message'=> $message, 'errors' => $errors],  400));

    }
}
