import { checkPermission } from "../permissions/check";
import { NextResponse } from "next/server";
const HTTP_TO_ACTION = {
  "GET": "read",
  // Single entity retrieval
  "POST": "create",
  "PATCH": "update",
  "PUT": "update",
  "DELETE": "delete"
};
const LIST_ACTION = "list";
function getEntityPermission(entitySlug, action) {
  return `${entitySlug}.${action}`;
}
function getActionFromMethod(method, isCollection) {
  if (method === "GET") {
    return isCollection ? LIST_ACTION : "read";
  }
  return HTTP_TO_ACTION[method] || "read";
}
async function checkEntityPermission(userId, teamId, entitySlug, action) {
  const permission = getEntityPermission(entitySlug, action);
  console.log(`[PermMiddleware] Checking permission: ${permission} for user ${userId} in team ${teamId}`);
  const hasPermission = await checkPermission(userId, teamId, permission);
  console.log(`[PermMiddleware] Result: ${hasPermission}`);
  if (!hasPermission) {
    return {
      allowed: false,
      error: NextResponse.json(
        {
          success: false,
          error: {
            message: `Permission denied: You do not have permission to ${action} ${entitySlug}`,
            code: "PERMISSION_DENIED",
            details: {
              requiredPermission: permission,
              entity: entitySlug,
              action
            }
          }
        },
        {
          status: 403,
          headers: { "Content-Type": "application/json" }
        }
      )
    };
  }
  return { allowed: true };
}
async function checkEntityPermissionOrFail(userId, teamId, entitySlug, method, isCollection) {
  const action = getActionFromMethod(method, isCollection);
  const result = await checkEntityPermission(userId, teamId, entitySlug, action);
  return result.allowed ? null : result.error;
}
export {
  LIST_ACTION,
  checkEntityPermission,
  checkEntityPermissionOrFail,
  getActionFromMethod,
  getEntityPermission
};
