<?php

namespace Modules\User\Requests\Api;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\DB;

class CheckCodeRequest extends FormRequest
{
    public function authorize()
    {
        return true; // Authorize the request for now
    }

    public function rules()
    {
        return [
            'phone' => [
                'required',
                'regex:/^9665\d{8}$/',
            ],
            'op' => ['required', 'in:forget_password,register'],
            'code' => ['required', 'min:4', 'max:4'],
        ];
    }

    protected function prepareForValidation()
    {
        $this->merge([
            'phone' => $this->input('phone'),
            'code' => $this->input('code'),
            'op' => $this->input('op'),
        ]);
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if (!$this->isValidVerificationRecord()) {
                $validator->errors()->add('phone', __('validation.exists', ['attribute' => __('users.phone')]));
            }
        });
    }

    private function isValidVerificationRecord()
    {
        return DB::table('verifications')
            ->where('phone', $this->input('phone'))
            ->where('code', $this->input('code'))
            ->where('op', $this->input('op'))
            ->exists();
    }

    public function attributes(): array
    {
        return [
            'op' => __('users.op'),
            'phone' => __('users.phone'),
            'code' => __('users.code'),
        ];
    }

    protected function failedValidation(Validator $validator)
    {
        $errors = (new ValidationException($validator))->errors();
        $message = $validator->errors()->first();
        throw new HttpResponseException(response()->json(['message' => $message, 'errors' => $errors], 400));
    }
}
