import prisma from "../config/prisma.js";

export class ForgotPasswordRepository {

    async findUserByEmail(email: string) {
        return prisma.user.findUnique({
            where: {
                email
            }
        })
    }

    async createOrUpdateOtp(userId: bigint, attempts: number = 5) {
        const otp = Math.floor(100000 + Math.random() * 900000).toString();
        const expiresAt = new Date(Date.now() + 15 * 60 * 1000);
        return prisma.forgotPassword.upsert({
            where: { userId },
            create: {
                userId,
                otp,
                attempts,
                expiresAt,
            },
            update: {
                otp,
                attempts,
                expiresAt,
            },
        });
    }

    async getOtpByEmail(email: string) {
        return prisma.forgotPassword.findFirst({
            where: {
                user: {
                    email,
                },
            },
            select: {
                userId: true,
                otp: true,
                attempts: true,
                expiresAt: true,
            },
        });
    }

    async updateAttempt(otpData: {
        userId: bigint;
        otp: string;
        attempts: number;
        expiresAt: Date;
    }) {
        return prisma.forgotPassword.update({
            where: { userId: otpData.userId },
            data: {
                attempts: { decrement: 1 }
            }
        })
    }

    async deleteOtp(userId: bigint) {
        return prisma.forgotPassword.delete({
            where: { userId }
        });
    }
}