import { NextFunction, Request, Response } from "express";
import { CatchAsyncError } from "./Catch";
import { getAuth, clerkClient } from "@clerk/express";
import { ApiError } from "./ApiError";
import { prisma } from "../utils/prisma";

export const authMiddleware = CatchAsyncError(async (req: Request, res: Response, next: NextFunction) => {




    const { userId, sessionId } = getAuth(req);


    // Check if userId and sessionId are present


    console.log("dfdfdddfdf", userId, sessionId)

    if (!userId || !sessionId) {

        throw new ApiError("Unauthorized", 401);
    }



    const session = await clerkClient.sessions.getSession(sessionId);


    if (session.status !== "active") {

        clerkClient.sessions.revokeSession(userId)

        throw new ApiError("Unauthorized", 401);
    }


    const checkUser = await prisma.user.findFirst({
        where: {
            clerkId: userId
        }
    });



    if (!checkUser) {
        clerkClient.sessions.revokeSession(userId)

        throw new ApiError("Unauthorized", 401);
    }

    req.user = checkUser

    next()
})