<?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(
        protected 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 (! $this->username || ! $value) {
            $fail(config()->string('module.otp-verification.no_username_or_code_message'));

            return;
        }

        OtpVerification::query()
            ->where('username', $this->username)
            ->where('code', $value)
            ->firstOr(fn () => $fail(config()->string('module.otp-verification.validation_message')));
    }
}
