import { Injectable, BadRequestException } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { OtpUtils } from 'src/common/utils/utils.otp';
import type { OtpVerification } from 'generated/prisma/client';
import { OtpType } from '../types/auth.types';

@Injectable()
export class OtpService {
    constructor(private readonly prismaService: PrismaService) { }

    async generateOtp(data: {
        userId: string;
        email: string;
        otpType: OtpType;
        phoneNumber?: string;
    }): Promise<OtpVerification> {
        const otpCode = OtpUtils.generateOtp();
        const expiredAt = OtpUtils.generateOtpExpiration(5); 

        return this.prismaService.otpVerification.create({
            data: {
                userId: data.userId,
                email: data.email,
                phoneNumber: data.phoneNumber,
                otpCode,
                otpType: data.otpType,
                expiredAt,
            },
        });
    }

    async verifyOtp(data: {
        userId: string;
        email: string;
        otpCode: string;
        otpType: OtpType;
    }): Promise<boolean> {
        const otp = await this.prismaService.otpVerification.findFirst({
            where: {
                userId: data.userId,
                email: data.email,
                otpCode: data.otpCode,
                otpType: data.otpType,
                isVerified: false,
            },
        });

        if (!otp) {
            throw new BadRequestException('Invalid OTP code');
        }

        if (!OtpUtils.isOtpValid(otp.expiredAt)) {
            throw new BadRequestException('OTP code has expired');
        }

        await this.prismaService.otpVerification.update({
            where: { id: otp.id },
            data: { isVerified: true },
        });

        return true;
    }

    async getLatestOtp(userId: string, otpType: OtpType) {
        return this.prismaService.otpVerification.findFirst({
            where: {
                userId,
                otpType,
                isVerified: false,
            },
            orderBy: {
                createdAt: 'desc',
            },
        });
    }

    async invalidateOtp(otpId: string): Promise<void> {
        await this.prismaService.otpVerification.update({
            where: { id: otpId },
            data: { isVerified: true },
        });
    }


    async cleanupExpiredOtps(): Promise<void> {
        await this.prismaService.otpVerification.deleteMany({
            where: {
                expiredAt: {
                    lt: new Date(),
                },
                isVerified: false,
            },
        });
    }
}
