import { NextResponse } from "next/server";
import { auth } from "../../auth.js";
import { validateApiKey } from "../auth.js";
import { queryOne } from "../../db.js";
import { TeamMemberService } from "../../services/team-member.service.js";
const SYSTEM_ADMIN_TEAM_ID = "team-nextspark-001";
const ADMIN_BYPASS_HEADER = "x-admin-bypass";
const ADMIN_BYPASS_VALUE = "confirm-cross-team-access";
const ELEVATED_ROLES = ["superadmin", "developer"];
async function getUserDefaultTeamId(userId) {
  try {
    const result = await queryOne(
      `SELECT "teamId" FROM "team_members"
       WHERE "userId" = $1
       ORDER BY "joinedAt" ASC
       LIMIT 1`,
      [userId]
    );
    return result == null ? void 0 : result.teamId;
  } catch (error) {
    console.error("[dual-auth] Failed to get default team:", error);
    return void 0;
  }
}
async function authenticateRequest(request) {
  const apiKeyResult = await tryApiKeyAuth(request);
  if (apiKeyResult.success) {
    return apiKeyResult;
  }
  const sessionResult = await trySessionAuth(request);
  if (sessionResult.success) {
    return sessionResult;
  }
  return {
    success: false,
    type: "none",
    user: null
  };
}
async function tryApiKeyAuth(request) {
  try {
    const authHeader = request.headers.get("authorization");
    const apiKeyHeader = request.headers.get("x-api-key");
    if (!(authHeader == null ? void 0 : authHeader.startsWith("Bearer ")) && !apiKeyHeader) {
      return { success: false, type: "none", user: null };
    }
    const apiAuth = await validateApiKey(request);
    if (!apiAuth) {
      return { success: false, type: "none", user: null };
    }
    const userInfo = await queryOne(
      'SELECT email, role, name FROM "users" WHERE id = $1',
      [apiAuth.userId]
    );
    const defaultTeamId = await getUserDefaultTeamId(apiAuth.userId);
    return {
      success: true,
      type: "api-key",
      user: {
        id: apiAuth.userId,
        email: (userInfo == null ? void 0 : userInfo.email) || "",
        role: (userInfo == null ? void 0 : userInfo.role) || "user",
        name: userInfo == null ? void 0 : userInfo.name,
        defaultTeamId
      },
      scopes: apiAuth.scopes || []
    };
  } catch (error) {
    console.error("API Key auth failed:", error);
    return { success: false, type: "none", user: null };
  }
}
async function trySessionAuth(request) {
  try {
    console.log("[dual-auth] Attempting session authentication...");
    const session = await auth.api.getSession({ headers: request.headers });
    console.log("[dual-auth] Session result:", session ? "found" : "not found");
    if (!(session == null ? void 0 : session.user)) {
      console.log("[dual-auth] No session.user found");
      return { success: false, type: "none", user: null };
    }
    const defaultTeamId = await getUserDefaultTeamId(session.user.id);
    console.log("[dual-auth] Session auth successful for user:", session.user.id);
    return {
      success: true,
      type: "session",
      user: {
        id: session.user.id,
        email: session.user.email,
        role: session.user.role || "user",
        name: session.user.name,
        defaultTeamId
      },
      scopes: ["all"]
      // Sessions have full access
    };
  } catch (error) {
    console.error("[dual-auth] Session auth failed with error:", error);
    return { success: false, type: "none", user: null };
  }
}
function hasRequiredScope(authResult, requiredScope) {
  if (authResult.type === "session") {
    return true;
  }
  if (authResult.type === "api-key" && authResult.scopes) {
    return authResult.scopes.includes(requiredScope) || authResult.scopes.includes("admin:all") || authResult.scopes.includes("*");
  }
  return false;
}
async function resolveTeamContext(request, authResult) {
  var _a;
  const teamId = request.headers.get("x-team-id") || ((_a = request.cookies.get("activeTeamId")) == null ? void 0 : _a.value) || authResult.user.defaultTeamId;
  if (!teamId) {
    return NextResponse.json(
      { success: false, error: "Team context required. Include x-team-id header." },
      { status: 400 }
    );
  }
  const isMember = await TeamMemberService.isMember(teamId, authResult.user.id);
  if (!isMember) {
    return NextResponse.json(
      { success: false, error: "Access denied: You are not a member of this team" },
      { status: 403 }
    );
  }
  return teamId;
}
async function canBypassTeamContext(authResult, request) {
  if (!authResult.success || !authResult.user) return false;
  const hasElevatedRole = ELEVATED_ROLES.includes(
    authResult.user.role
  );
  if (!hasElevatedRole) return false;
  const bypassHeader = request.headers.get(ADMIN_BYPASS_HEADER);
  if (bypassHeader !== ADMIN_BYPASS_VALUE) return false;
  const isMember = await checkSystemAdminMembership(authResult.user.id);
  if (!isMember) {
    console.log("[dual-auth] User has elevated role but is not member of System Admin Team");
  }
  return isMember;
}
async function checkSystemAdminMembership(userId) {
  try {
    const member = await queryOne(
      'SELECT id FROM "team_members" WHERE "teamId" = $1 AND "userId" = $2',
      [SYSTEM_ADMIN_TEAM_ID, userId]
    );
    return !!member;
  } catch (error) {
    console.error("[dual-auth] Failed to check system admin membership:", error);
    return false;
  }
}
function createAuthError(message = "Authentication required", status = 401) {
  return NextResponse.json(
    {
      success: false,
      error: message,
      code: "AUTHENTICATION_FAILED"
    },
    { status }
  );
}
export {
  ADMIN_BYPASS_HEADER,
  ADMIN_BYPASS_VALUE,
  SYSTEM_ADMIN_TEAM_ID,
  authenticateRequest,
  canBypassTeamContext,
  createAuthError,
  hasRequiredScope,
  resolveTeamContext
};
