<?php

namespace App\Utils;

use App\Models\OTP;
use App\Models\User;

trait ManagesOTP {

    public function createOTP(User $user, $purpose): OTP {
        $user->otps()->latest()->first()?->invalidate();
        $otp = $user->otps()->create([
            'code' => generate_otp(),
            'purpose' => $purpose,
            'expires_at' => now()->addMinutes((int) setting('otp_expiration')),
        ]);

        return $otp;
    }

    public function OTPIsInvalid(User $user, $code, $purpose) {
        $otp = $user->otps()->where('purpose', $purpose)->first();
        if($otp->code != $code) {
            return true;
        }
        if($otp->expires_at->isPast()) {
            return true;
        }
    }

    private function invalidateOTP(OTP $otp) {
        if($otp->expires_at->isFuture()) {
            $otp->invalidate();
        }
    }
}