import type { Request, Response } from 'express';
import asyncHandler from 'express-async-handler';
import bcrypt from 'bcrypt';
import { v4 as uuidv4 } from 'uuid';
import { prisma } from '../config/db.ts';
import { sendEmail } from '../utils/mail.ts';
import { verificationTemplate } from '../utils/verificationMail.ts';
import { forgotPasswordTemplate } from '../utils/forgotPassword.ts';
import crypto from "crypto";
import { getHost, signToken } from '../utils/utils.ts';
import { toIST, tokenExpireTime, trailExpireTimeDays } from '../utils/time.ts';

// Student register from mobile app
export const registerStudent = asyncHandler(async (req: Request, res: Response) => {
    const { firstName, lastName, email, phone, password } = req.body;
    if (true) {
        res.status(201).json({
            message: "Temporarily blocked from registration.",
        });
        return;
    }
    if (!firstName) {
        res.status(400).json({ message: "First name is required" });
        return;
    }

    if (!lastName) {
        res.status(400).json({ message: "Last name is required" });
        return;
    }

    if (!email) {
        res.status(400).json({ message: "Email is required" });
        return;
    }

    if (!password) {
        res.status(400).json({ message: "Password is required" });
        return;
    }

    const exists = await prisma.user.findFirst({ where: { email } });
    if (exists) {
        res.status(400).json({ message: "Email already registered" });
        return;
    }

    const admin = await prisma.user.findFirst({ where: { role: 'ADMIN' } });

    if (!admin) {
        res.status(500).json({ message: "Admin account not found" });
        return;
    }

    const adminId = admin.id;
    const hash = await bcrypt.hash(password, 10);

    // Trial plan check
    // const trialPlan = await prisma.subscriptionPlan.findFirst({ where: { isActive: true, planType: "trial" } })
    // if (!trialPlan) {
    //     res.status(201).json({
    //         message: "Trial plan not found, please contact organization",
    //     });
    // }

    // Create User
    const user = await prisma.user.create({
        data: {
            firstName,
            lastName,
            email,
            phone,
            password: hash,
            role: "STUDENT",
            isVerified: false,
            createdById: adminId,
            expiresAt: tokenExpireTime(),
        }
    });

    await prisma.student.create({
        data: {
            userId: user.id,
            // institutionId: null,
            // expiresAt: tokenExpireTime(),
            // subscriptionPlanId: trialPlan.id
        }
    });

    const tokenStr = uuidv4();
    await prisma.token.create({
        data: {
            userId: user.id,
            token: tokenStr,
            type: "VERIFY",
            expiresAt: tokenExpireTime(),
        }
    });

    const verifyUrl = `${process.env.BASE_URL}/verify/${tokenStr}`;

    await sendEmail(
        email,
        "Verify your email",
        verificationTemplate({ firstName, companyName: "ExamInfra", verifyUrl })
    );

    res.status(201).json({
        message: "Registered. Check your email to verify your account.",
    });
});

// Register Institution
export const registerInstitution = asyncHandler(async (req: Request, res: Response) => {
    const { contactPerson, institutionName, institutionAddress, email, phone, password, state, pincode } = req.body;

    const isEmpty = (value: any) => value === undefined || value === null || value.toString().trim() === "";

    const requiredFields = [
        { key: "institutionName", message: "Institution name is required" },
        { key: "institutionAddress", message: "Institution address is required" },
        { key: "contactPerson", message: "Contact person is required" },
        { key: "email", message: "Email is required" },
        { key: "password", message: "Password is required" },
        { key: "state", message: "State is required" },
        { key: "pincode", message: "Pincode is required" },
    ];

    for (const field of requiredFields) {
        if (isEmpty(req.body[field.key])) {
            res.status(400).json({ message: field.message });
            return;
        }
        if (field.key === "phone" && req.body[field.key].length !== 10) {
            res.status(400).json({ message: "Phone number must be 10 digits" });
            return;
        }
        if (field.key === "pincode" && req.body[field.key].length !== 6) {
            res.status(400).json({ message: "Pincode must be 6 digits" });
            return;
        }
    }

    const exists = await prisma.user.findFirst({ where: { email } });
    if (exists) {
        res.status(400).json({ message: "Email already registered" });
        return;
    }

    const hash = await bcrypt.hash(password, 10);
    const user = await prisma.user.create({
        data: {
            institutionName: String(institutionName).trim(),
            institutionAddress,
            contactPerson,
            email,
            phone,
            password: hash,
            state,
            pincode,
            role: "INSTITUTION",
            isVerified: false,
            expiresAt: tokenExpireTime(),
        }
    });

    const tokenStr = uuidv4();
    await prisma.token.create({
        data: {
            userId: user.id,
            token: tokenStr,
            type: "VERIFY",
            expiresAt: tokenExpireTime(),
        }
    });

    const verifyUrl = `${process.env.BASE_URL}/verify/${tokenStr}`;

    await sendEmail(
        email,
        "Verify your email",
        verificationTemplate({ firstName: institutionName || "", companyName: "ExamInfra", verifyUrl })
    );

    res.status(201).json({
        message: "Registered. Check your email to verify your account.",
    });
});

// Verify Email
// export const verifyEmail = asyncHandler(async (req: Request, res: Response) => {
//     const { token } = req.params;

//     const dbToken = await prisma.token.findFirst({
//         where: { token, type: "VERIFY" }
//     });

//     if (!dbToken) {
//         res.status(400).json({ message: "Invalid or expired token" });
//         return;
//     }

//     const user = await prisma.user.findUnique({ where: { id: dbToken.userId } });
//     if (!user) {
//         res.status(400).json({ message: "User not found" });
//         return;
//     }

//     // Update user
//     await prisma.user.update({
//         where: { id: user.id },
//         data: {
//             isVerified: true,
//             expiresAt: null
//         }
//     });

//     // Update student expiresAt if exists
//     await prisma.student.updateMany({
//         where: { userId: user.id },
//         data: { expiresAt: null }
//     });

//     // Delete token
//     await prisma.token.delete({ where: { id: dbToken.id } });

//     if (user.role === "STUDENT") {
//         const existingStudent = await prisma.student.findUnique({ where: { userId: user.id } });
//         if (!existingStudent) {
//             let institutionId = null;
//             if (user.createdById) {
//                 const institution = await prisma.institution.findUnique({
//                     where: { userId: user.createdById }
//                 });
//                 if (institution) {
//                     institutionId = institution.id;
//                 }
//             }
//             await prisma.student.create({
//                 data: {
//                     userId: user.id,
//                     institutionId: institutionId,
//                 }
//             });
//         }
//     } else if (user.role === "INSTITUTION") {
//         const existingInst = await prisma.institution.findUnique({ where: { userId: user.id } });
//         if (!existingInst) {
//             await prisma.institution.create({
//                 data: {
//                     userId: user.id,
//                 }
//             });
//         }
//     }else if (user.role === "STAFF") {
//         const existingStaff = await prisma.staff.findUnique({ where: { userId: user.id } });
//         if (!existingStaff) {
//             let institutionId = null;
//             if (user.createdById) {
//                 const institution = await prisma.institution.findUnique({
//                     where: { userId: user.createdById }
//                 });
//                 if (institution) {
//                     institutionId = institution.id;
//                 }
//             }
//             await prisma.staff.create({
//                 data: {
//                     userId: user.id,
//                     institutionId: institutionId,
//                 }
//             });
//         }
//     }

//     res.status(201).json({ message: "Email verified successfully!" });
// });

export const verifyEmail = asyncHandler(async (req: Request, res: Response) => {
    const { token } = req.params;

    await prisma.$transaction(async (tx) => {
        const dbToken = await tx.token.findFirst({
            where: {
                token,
                type: { in: ["VERIFY", "STUDENTVERIFY"] },
                expiresAt: {
                    gt: new Date(),
                }
            },
        });

        if (!dbToken) {
            const err: any = new Error("Invalid or expired token");
            err.statusCode = 400;
            throw err;
        }

        const user = await tx.user.findUnique({
            where: { id: dbToken.userId },
        });

        if (!user) {
            const err: any = new Error("User not found");
            err.statusCode = 404;
            throw err;
        }

        // resolve institutionId

        let institutionId: string | null = null;

        if (user.createdById) {
            const institution = await tx.institution.findUnique({
                where: { userId: user.createdById },
                select: { id: true },
            });

            if (institution) {
                institutionId = institution.id;
            } else {
                const staff = await tx.staff.findUnique({
                    where: { userId: user.createdById },
                    select: { institutionId: true },
                });

                institutionId = staff?.institutionId ?? null;
            }
        }

        // for staff and student users
        if (user.role !== "INSTITUTION" && !institutionId) {
            const err: any = new Error("Institution not found. Please contact admin for more details.");
            err.statusCode = 404;
            throw err;
        }

        await tx.user.update({
            where: { id: user.id },
            data: {
                isVerified: true,
                expiresAt: null,
            },
        });

        if (user.role === "INSTITUTION") {
            await tx.institution.upsert({
                where: { userId: user.id },
                update: {},
                create: { userId: user.id },
            });
        }

        if (user.role === "STAFF") {
            await tx.staff.upsert({
                where: { userId: user.id },
                update: {},
                create: { userId: user.id, institutionId },
            });
        }

        if (user.role === "STUDENT") {
            if (!dbToken.studentInstitutionId || !dbToken.institutionId) {
                const err: any = new Error("Institution not found. Please contact admin for more details.");
                err.statusCode = 404;
                throw err;
            } else {
                institutionId = dbToken.institutionId
            }
            const student = await tx.student.upsert({
                where: { userId: user.id },
                update: {},
                create: { userId: user.id },
                include: { user: true },
            });

            await tx.studentInstitution.updateMany({
                where: { studentId: student.id },
                data: {
                    isPrimary: false
                }
            });

            await tx.studentInstitution.update({
                where: { id: dbToken.studentInstitutionId },
                data: {
                    isPrimary: true,
                    isVerified: true,
                    verificationExpiresAt: null,
                },
            });


            const existingSubscripion = await tx.subscription.findFirst({
                where: {
                    institutionId: institutionId,
                    studentInstitutionId: dbToken.studentInstitutionId,
                    email: student.user.email,
                    isCurrent: true
                },
                orderBy: {
                    createdAt: "desc",
                }
            });

            if (!existingSubscripion) {
                const trialPlan = await tx.subscriptionPlan.findFirst({
                    where: {
                        planType: "trial",
                        isActive: true
                    },
                    orderBy: {
                        createdAt: "desc",
                    },
                });
                if (!trialPlan) {
                    const err: any = new Error("Trial plan not found");
                    err.statusCode = 404;
                    throw err;
                }
                const startDate = new Date();
                const endDate = new Date();
                endDate.setDate(endDate.getDate() + trialPlan.duration);

                await tx.subscription.create({
                    data: {
                        student: {
                            connect: {
                                id: student.id,
                            },
                        },
                        email: student.user.email,
                        amount: 0,
                        chargedAmount: 0,
                        creditUsed: 0,
                        startDate,
                        endDate,
                        status: "ACTIVE",
                        action: "TRIAL",
                        isCurrent: true,
                        plan: {
                            connect: {
                                id: trialPlan.id,
                            },
                        },
                        institution: {
                            connect: {
                                id: institutionId,
                            },
                        },
                        studentInstitution: {
                            connect: {
                                id: dbToken.studentInstitutionId
                            }
                        }
                    },
                });
            } else {
                await tx.subscription.update({
                    where: {
                        id: existingSubscripion.id,
                    },
                    data: {
                        studentId: student.id,
                        institutionId: institutionId,
                        planId: existingSubscripion.planId,
                    },
                });

            }
        }

        await tx.token.delete({
            where: { id: dbToken.id },
        });
    });

    res.status(201).json({
        success: true,
        message: "Email verified successfully!",
    });
});

// Login
export const login = asyncHandler(async (req: Request, res: Response) => {
    const { email, password } = req.body;

    if (!email) {
        res.status(400).json({ message: 'Email is required' });
        return;
    }
    if (!password) {
        res.status(400).json({ message: 'Password is required' });
        return;
    }

    const user = await prisma.user.findFirst({
        where: {
            email: {
                equals: String(email ?? '').trim().toLowerCase(),
                not: null,
            },
            isDeleted: false,
        }
    });
    if (!user) {
        res.status(404).json({ message: 'User not found, Please register first' });
        return;
    }

    if (user.role === "STUDENT") {
        res.status(403).json({ message: 'Invalid user' });
        return;
    }

    if (!user.isVerified) {
        let institutionId: string | null = null;

        if (user.role === "STAFF") {
            const staff = await prisma.staff.findUnique({
                where: { userId: user.id },
                select: { institutionId: true },
            });
            institutionId = staff?.institutionId ?? null;

            if (!institutionId && user.createdById) {
                const institution = await prisma.institution.findUnique({
                    where: { userId: user.createdById },
                    select: { id: true },
                });
                institutionId = institution?.id ?? null;
            }
        } else if (user.role === "INSTITUTION") {
            const institution = await prisma.institution.findUnique({
                where: { userId: user.id },
                select: { id: true },
            });
            institutionId = institution?.id ?? null;
        }

        const verifyToken = await prisma.token.findFirst({
            where: {
                userId: user.id,
                type: "VERIFY",
            },
            orderBy: { createdAt: "desc" },
        });

        const shouldResendVerification = !verifyToken || (verifyToken && new Date() > verifyToken.expiresAt);

        if (shouldResendVerification) {
            const tokenStr = uuidv4();
            await prisma.token.create({
                data: {
                    userId: user.id,
                    token: tokenStr,
                    type: "VERIFY",
                    institutionId: institutionId ?? undefined,
                    expiresAt: tokenExpireTime(),
                }
            });

            const verifyUrl = `${process.env.BASE_URL}/verify/${tokenStr}`;
            const displayName = user.institutionName || [user.firstName, user.lastName].filter(Boolean).join(" ") || "there";

            const emailRes = await sendEmail(
                user.email,
                "Verify your email",
                verificationTemplate({ firstName: displayName, companyName: "ExamInfra", verifyUrl })
            );
            if (!emailRes.success) {
                res.status(500).json({ message: "Failed to send verification email. Please try again later." });
                return;
            }

            res.status(403).json({ message: "Your verification link has expired. A new link has been sent to your email." });
            return;
        }

        res.status(403).json({ message: 'Email not verified' });
        return;
    }

    const match = await bcrypt.compare(password, user.password);
    if (!match) {
        res.status(400).json({ message: 'Invalid credentials' });
        return;
    }

    const { firstName, lastName, role, phone, id, isVerified, institutionName, institutionAddress, logoPic, profilePic, contactPerson, createdAt, updatedAt, state, pincode } = user;
    let response: any = {
        id,
        firstName,
        lastName,
        role,
        phone,
        email,
        state,
        pincode,
        profilePic: profilePic ? `${getHost()}${profilePic}` : "",
        isVerified,
        institutionName,
        institutionAddress,
        logoPic: logoPic ? `${getHost()}${logoPic}` : "",
        contactPerson,
        createdAt: toIST(createdAt),
        updatedAt: toIST(updatedAt),
        institutionId: null
    };

    if (role === "STAFF") {
        const staff = await prisma.staff.findUnique({
            where: { userId: id }, include: { role: true }
        });
        response.institutionId = staff?.institutionId;

        const institution = await prisma.user.findUnique({ where: { id: user.createdById as string } });
        response.institutionName = institution?.institutionName;
        response.institutionAddress = institution?.institutionAddress;
        response.logoPic = institution?.logoPic ? `${getHost()}${institution?.logoPic}` : "";
        response.contactPerson = institution?.contactPerson;
        response.permissions = staff?.role.permissions;
        response.referralCode = staff?.referralCode;
    } else if (role === "INSTITUTION") {
        const institution = await prisma.institution.findUnique({
            where: { userId: id }
        });
        if(!institution) {
        res.status(404).json({ message: 'Institution not found' });
            return
        }
        response.institutionId = institution?.id;
    }

    const sessionToken = crypto.randomBytes(32).toString("hex");

    await prisma.user.update({
        where: { id: user.id },
        data: { sessionToken }
    });

    const token = signToken({ ...user, institutionId: response.institutionId }, sessionToken);

    res.json({
        message: "Login Successfully",
        token,
        user: response
    });
});

// Student Login
export const studentLogin = asyncHandler(async (req: Request, res: Response) => {
    const { email, password } = req.body;

    if (!email) {
        res.status(400).json({ message: 'Email is required' });
        return;
    }
    if (!password) {
        res.status(400).json({ message: 'Password is required' });
        return;
    }

    const user = await prisma.user.findFirst({ where: { email, isDeleted: false } });

    if (!user) {
        res.status(401).json({ message: 'User not found, Please register first' });
        return;
    }

    if (user.role !== "STUDENT") {
        res.status(401).json({ message: 'Invalid user' });
        return;
    }
    const match = await bcrypt.compare(String(password).trim(), user.password);
    if (!match) {
        res.status(400).json({ message: 'Invalid credentials' });
        return;
    }

    const student = await prisma.student.findUnique({
        where: { userId: user.id },
        include: {
            institutions: {
                take: 1,
                where: { deletedAt: null, isPrimary: true },
                include: {
                    exam: { select: { id: true, examName: true } },
                    institution: {
                        select: {
                            user: {
                                select: { institutionName: true, logoPic: true, institutionAddress: true }
                            }
                        }
                    },
                    subscriptions: {
                        where: { isCurrent: true }
                    },

                },
            }
        }
    });
    const studentTrialPlan = await prisma.subscription.findFirst({
        where: { studentId: student?.id, action: "TRIAL" },
        orderBy: { createdAt: "asc" },
    });

    if (!student) {
        res.status(401).json({ message: 'Student not found' });
        return;
    }

    if (!student.institutions[0]) {
        res.status(403).json({ message: 'Primary institution not found' });
        return;
    }

    if (!student.institutions[0].isVerified) {
        const verifyToken = await prisma.token.findFirst({
            where: {
                userId: user.id,
                type: "VERIFY",
                studentInstitutionId: student.institutions[0].id
            },
            orderBy: { createdAt: "desc" }
        });

        const shouldResendVerification = !verifyToken || (verifyToken && new Date() > verifyToken.expiresAt);

        if (shouldResendVerification) {
            const tokenStr = uuidv4();
            await prisma.token.create({
                data: {
                    userId: user.id,
                    token: tokenStr,
                    institutionId: student.institutions[0].institutionId,
                    studentInstitutionId: student.institutions[0].id,
                    type: "VERIFY",
                    expiresAt: tokenExpireTime(),
                }
            });

            const verifyUrl = `${process.env.BASE_URL}/verify/${tokenStr}`;
            const emailRes = await sendEmail(
                user.email,
                "Verify your email",
                verificationTemplate({ firstName: user.firstName, companyName: "ExamInfra", verifyUrl })
            );
            if (!emailRes.success) {
                res.status(500).json({ message: "Failed to send verification email. Please try again later." });
                return;
            }

            res.status(403).json({ message: "Your verification link has expired. A new link has been sent to your email." });
            return;
        }

        res.status(403).json({ message: 'Email not verified' });
        return;
    }

    const { firstName, lastName, role, phone, id } = user;
    let response: any = { id, firstName, lastName, role, phone, email };

    const sessionToken = crypto.randomBytes(32).toString("hex");

    await prisma.user.update({
        where: { id: user.id },
        data: { sessionToken }
    });

    const primaryInst = student.institutions[0];
    const tokenStudentInstId = primaryInst?.id;
    const token = signToken({ ...user, institutionId: tokenStudentInstId }, sessionToken);

    const createdByUser = await prisma.user.findUnique({ where: { id: user.createdById } });
    response.isInstitution = createdByUser?.role === "INSTITUTION" ? true : false;
    response.institutionName = createdByUser?.institutionName ?? "";
    response.institutionAddress = createdByUser?.institutionAddress ?? "";
    response.institutionLogo = createdByUser?.logoPic ? `${getHost()}${createdByUser?.logoPic}` : "";

    res.json({
        message: "Login Successfully",
        token,
        user: {
            ...response,
            language: student?.language || primaryInst?.language || "",
            mediumOfExam: student?.language ? (primaryInst?.language || "English") : "English",
            examId: primaryInst?.exam?.id ?? "",
            examName: primaryInst?.exam?.examName ?? "",
            studentInstitutionId: primaryInst ? primaryInst.id : null,
            // institutions: student.institutions.map(inst => ({
            //     id: inst.institutionId,
            //     name: inst.institution?.user?.institutionName ?? "",
            //     logo: inst.institution?.user?.logoPic ? `${getHost()}${inst.institution?.user?.logoPic}` : "",
            //     address: inst.institution?.user?.institutionAddress ?? "",
            //     isPrimary: inst.isPrimary,
            //     examId: inst.examsId,
            //     examName: inst.exam?.examName ?? "",
            //     language: inst.language ?? "",
            // })),
            subscription: primaryInst.subscriptions[0] ? {
                ...primaryInst.subscriptions[0],
                amount: Number(primaryInst.subscriptions[0].amount),
                chargedAmount: Number(primaryInst.subscriptions[0].chargedAmount),
                creditUsed: Number(primaryInst.subscriptions[0].creditUsed),
                startDate: primaryInst.subscriptions[0].startDate ? toIST(primaryInst.subscriptions[0].startDate) : null,
                endDate: primaryInst.subscriptions[0].endDate ? toIST(primaryInst.subscriptions[0].endDate) : null,
                trialEndsAt: studentTrialPlan?.endDate ? toIST(studentTrialPlan.endDate) : null,
                createdAt: toIST(primaryInst.subscriptions[0].createdAt),
            } : "",
            profilePic: user.profilePic ? `${getHost()}${user.profilePic}` : "",
        }
    });
});

// Change Password
export const changePassword = asyncHandler(async (req: Request, res: Response) => {
    const { oldPassword, newPassword } = req.body;
    const userId = (req as any).user.id;

    const user = await prisma.user.findUnique({ where: { id: userId } });
    if (!user) {
        res.status(404).json({ message: 'User not found' });
        return;
    }
    const match = await bcrypt.compare(oldPassword, user.password);
    if (!match) {
        res.status(400).json({ message: 'Old password incorrect' });
        return;
    }
    const hash = await bcrypt.hash(newPassword, 10);

    await prisma.user.update({
        where: { id: userId },
        data: { password: hash }
    });

    res.json({ message: 'Password changed' });
});

// Forgot Password
export const forgotPassword = asyncHandler(async (req: Request, res: Response) => {
    const { email } = req.body;
    if (!email) {
        res.status(400).json({ message: 'Email is required' });
        return
    }
    const user = await prisma.user.findFirst({ where: { email } });
    if (!user) {
        res.status(404).json({ message: 'No user with that email' });
        return
    }

    const tokenStr = uuidv4();
    await prisma.token.create({
        data: {
            userId: user.id,
            token: tokenStr,
            type: "RESET",
            expiresAt: tokenExpireTime()
        }
    });

    const verifyUrl = `${process.env.BASE_URL}/forgot-password/${tokenStr}`;
    const emailRes = await sendEmail(user.email, 'Password reset', forgotPasswordTemplate({ companyName: "ExamInfra", verifyUrl }));
    if (!emailRes.success) {
        res.status(500).json({ message: "Failed to send password reset email. Please try again later." });
        return;
    }
    res.json({ message: 'Password reset email sent' });
});

// Reset Password
export const resetPassword = asyncHandler(async (req: Request, res: Response) => {
    const { token } = req.params;
    const { password } = req.body;

    const dbToken = await prisma.token.findFirst({ where: { token, type: 'RESET', expiresAt: { gt: new Date() } } });
    if (!dbToken) {
        res.status(400).json({ message: 'Invalid or expired token' });
        return
    }

    const user = await prisma.user.findUnique({ where: { id: dbToken.userId } });
    if (!user) {
        res.status(404).json({ message: 'User not found' });
        return
    }

    const hash = await bcrypt.hash(password, 10);
    await prisma.user.update({
        where: { id: user.id },
        data: { password: hash }
    });

    await prisma.token.delete({ where: { id: dbToken.id } });
    res.json({ message: 'Password reset successful' });
});

// Register Admin
export const registerAdmin = asyncHandler(async (req: Request, res: Response) => {
    const { firstName, lastName, email, password } = req.body;

    if (!firstName) {
        res.status(400).json({ message: "First name is required" });
        return;
    }
    if (!email) {
        res.status(400).json({ message: "Email is required" });
        return;
    }
    if (!password) {
        res.status(400).json({ message: "Password is required" });
        return;
    }

    const exists = await prisma.user.findFirst({ where: { email } });
    if (exists) {
        res.status(400).json({ message: "Email already registered" });
        return;
    }
    const hash = await bcrypt.hash(password, 10);

    const admin = await prisma.user.create({
        data: {
            firstName,
            lastName,
            email,
            password: hash,
            role: "ADMIN",
            isVerified: true,
        }
    });

    res.status(201).json({
        message: "Admin registered successfully",
        user: {
            id: admin.id,
            firstName,
            lastName,
            email,
            role: "ADMIN",
            isVerified: true,
        },
    });
});

// Get Me
export const getMe = asyncHandler(async (req, res) => {
    const userId = (req as any).user.id;
    const user = await prisma.user.findUnique({ where: { id: userId } });

    if (!user) {
        res.status(401).json({ tokenValid: false, message: "Your session has expired. Please login again." });
        return;
    }
    res.json({
        tokenValid: true,
        message: "Valid token",
        data: {
            id: user.id,
            firstName: user.firstName,
            lastName: user.lastName,
            email: user.email,
            role: user.role,
        }
    });
});
