<?php

namespace App\Modules\OtpVerification\Repositories;

use App\Modules\OtpVerification\Models\OtpVerification;
use App\Modules\Sms\Repositories\SmsRepository;

class OtpVerificationRepository
{
    /**
     * Send a sms verification
     */
    public static function sendSMSVerification(string|int $phone_number): ?OtpVerification
    {
        abort_unless(module('Sms')->isEnabled(), 500, 'Sms module is not enabled');

        /* for apple testing */
        $phone_code = ($phone_number == config('module.otp-verification.apple_testing_phone'))
                        ? config()->integer('module.otp-verification.apple_testing_code')
                        : rand(config()->integer('module.otp-verification.min_code'), config()->integer('module.otp-verification.max_code'));

        $verification = OtpVerification::where(['username' => $phone_number])->first();
        $verification
            ? $verification->update(['code' => $phone_code])
            : OtpVerification::create(['username' => $phone_number, 'code' => $phone_code]);

        SmsRepository::sendSMS($phone_number, str_replace(':code', (string) $phone_code, config()->string('module.otp-verification.message')));

        return $verification;
    }
}
