<?php

namespace Modules\User\Requests\Admin;

use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Hash;
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.
     * So the user must be guest
     * @return bool
     */
    public function authorize()
    {
        return ! Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            'email'     => ['required', 'email', 'email'],
            'password'  => ['required', 'string', 'min:3'],
        ];
        if (request('email') && request('password'))
        {
            $user = $this->userService->getItemByEmail(request('email'));
            if ($user)
            {
                if (Hash::check(request('password'), $user->password))
                {
                    if($user->verified == 0)
                    {
                        $rules['new_password'] = ['required', 'string', 'min:3'];
                    }
                }
                else
                {
                    $rules['incorrect_password'] = ['required'];
                }
            }
            else
            {
                $rules['incorrect_password'] = ['required'];
            }
        }
        return $rules;
    }

    public function messages()
    {
        return
        [
            'incorrect_password.required' => 'Please Check Your Input.',
        ];
    }
}
