<?php

namespace App\Http\Requests\Auth;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Validator;

class UpdateTwoFactorRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return [
            'two_factor_enabled' => ['required', 'boolean'],
            'current_password' => ['required', 'string'],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            if (! Hash::check($this->input('current_password', ''), (string) $this->user()?->password)) {
                $validator->errors()->add('current_password', 'The current password is incorrect.');
            }

            if ($this->boolean('two_factor_enabled') && blank($this->user()?->phone)) {
                $validator->errors()->add('phone', 'Add a mobile number to your profile before enabling two-factor authentication.');
            }
        });
    }

    protected function getRedirectUrl(): string
    {
        return route('profile.edit');
    }
}
