<?php

namespace App\Modules\OTPVerification\Rules;

use App\Modules\OTPVerification\Models\OTPVerification;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class OTPVerificationRule implements ValidationRule
{
    public function __construct(public null|int|string $username)
    {
    }

    /**
     * Run the validation rule.
     *
     * @param  \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (! $value || ! $this->username) {
            $fail(__('Write a correct data please'));

            return;
        }

        OTPVerification::where('username', $this->username)
            ->where('code', $value)
            ->existsOr(fn () => $fail(__('Write a correct data please')));
    }
}
