import type { NextFunction, Response } from "express";
import { prisma, withPrismaRetry } from "../prisma.js";
import { userHasEffectivePermission } from "../services/effectivePermissions.js";
import type { AuthedRequest } from "./auth.js";

type RequirePermissionOptions = {
  projectIdParam?: string;
};

export function requirePermission(permissionKey: string, options?: RequirePermissionOptions) {
  return async (req: AuthedRequest, res: Response, next: NextFunction) => {
    const userId = req.auth?.userId;
    if (!userId) {
      res.status(401).json({ error: "Unauthorized" });
      return;
    }

    const projectIdParam = options?.projectIdParam;
    const projectIdRaw = projectIdParam ? req.params[projectIdParam] : undefined;
    const scopedProjectId = projectIdRaw ? BigInt(projectIdRaw) : null;

    const membership = await withPrismaRetry(() =>
      prisma.projectUser.findFirst({
      where: {
        userId,
        ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
      },
      select: { id: true, projectRole: true },
    }),
    );

    if (!membership) {
      res.status(403).json({ error: `Missing permission: ${permissionKey}` });
      return;
    }

    const allowed = await userHasEffectivePermission(prisma, userId, scopedProjectId, permissionKey);
    if (!allowed) {
      res.status(403).json({ error: `Missing permission: ${permissionKey}` });
      return;
    }

    next();
  };
}

