<?php

namespace App\Services;

use App\Enums\OtpVerificationResult;
use App\Models\PhoneVerification;
use Illuminate\Support\Facades\Hash;

class OtpService
{
    public const OTP_EXPIRY_MINUTES = 10;

    public function issue(string $phone): bool
    {
        $otp = $this->generateOtp();

        PhoneVerification::query()->updateOrCreate(
            ['phone' => $phone],
            [
                'otp' => Hash::make($otp),
                'expires_at' => now()->addMinutes(self::OTP_EXPIRY_MINUTES),
                'verified' => false,
            ],
        );

        return sendSMS($phone, 'Tassyklaýyş belgi: '.$otp);
    }

    public function verify(string $phone, string $otp): OtpVerificationResult
    {
        $verification = PhoneVerification::query()->where('phone', $phone)->first();

        if (! $verification) {
            return OtpVerificationResult::Invalid;
        }

        if ($verification->expires_at->isPast()) {
            return OtpVerificationResult::Expired;
        }

        if (! Hash::check($otp, $verification->otp)) {
            return OtpVerificationResult::Invalid;
        }

        $verification->update(['verified' => true]);

        return OtpVerificationResult::Verified;
    }

    private function generateOtp(): string
    {
        return (string) random_int(1000, 9999);
    }
}
