/**
 * V3 API auth — session (browser) or API key with workspace-scoped access.
 */
import { logger } from "@formbricks/logger";
import type { TAuthenticationApiKey } from "@formbricks/types/auth";
import { AuthorizationError, ResourceNotFoundError } from "@formbricks/types/errors";
import { type TAuthorizationActor, assertCan, can } from "@/lib/authorization";
import {
  type TWorkspaceAccessLevel,
  getWorkspaceAuthorizationAction,
} from "@/lib/authorization/permission-action";
import { problemForbidden, problemUnauthorized } from "./response";
import type { TV3Authentication } from "./types";
import { type V3WorkspaceContext, resolveV3WorkspaceContext } from "./workspace-context";

export const getV3AuthorizationActor = (authentication: TV3Authentication): TAuthorizationActor | null => {
  if (authentication && "user" in authentication && authentication.user?.id) {
    return { type: "user", id: authentication.user.id };
  }

  if (authentication && "apiKeyId" in authentication && authentication.apiKeyId) {
    return { type: "apiKey", id: authentication.apiKeyId };
  }

  return null;
};

/** The signed-in user behind a session request, or `null` for an API key: who a write records as creator. */
export const getV3SessionUserId = (authentication: TV3Authentication): string | null =>
  authentication && "user" in authentication && authentication.user?.id ? authentication.user.id : null;

/**
 * Require session and workspace access. workspaceId is resolved via the V3 workspace-context layer.
 * Returns a Response (401 or 403) on failure, or the resolved workspace context on success so callers
 * use internal IDs (workspaceId, organizationId) without resolving again.
 * We use 403 (not 404) when the workspace is not found to avoid leaking resource existence.
 */
export async function requireSessionWorkspaceAccess(
  authentication: TV3Authentication,
  workspaceId: string,
  minPermission: TWorkspaceAccessLevel,
  requestId: string,
  instance?: string
): Promise<Response | V3WorkspaceContext> {
  // --- Session checks ---
  if (!authentication) {
    return problemUnauthorized(requestId, "Not authenticated", instance);
  }
  if (!("user" in authentication) || !authentication.user?.id) {
    return problemUnauthorized(requestId, "Session required", instance);
  }

  const userId = authentication.user.id;
  const log = logger.withContext({ requestId, workspaceId });

  try {
    // Resolve workspaceId → workspaceId, organizationId (single place to change when Workspace exists).
    const context = await resolveV3WorkspaceContext(workspaceId);

    await assertCan({ type: "user", id: userId }, getWorkspaceAuthorizationAction(minPermission), {
      type: "workspace",
      id: context.workspaceId,
    });

    return context;
  } catch (err) {
    if (err instanceof ResourceNotFoundError || err instanceof AuthorizationError) {
      const message = err instanceof ResourceNotFoundError ? "Workspace not found" : "Forbidden";
      log.warn({ statusCode: 403, errorCode: err.name }, message);
      return problemForbidden(requestId, "You are not authorized to access this resource", instance);
    }
    throw err;
  }
}

/** Session or API key: authorize `workspaceId` against the resolved V3 workspace context. */
export async function requireV3WorkspaceAccess(
  authentication: TV3Authentication,
  workspaceId: string,
  minPermission: TWorkspaceAccessLevel,
  requestId: string,
  instance?: string
): Promise<Response | V3WorkspaceContext> {
  if (!authentication) {
    return problemUnauthorized(requestId, "Not authenticated", instance);
  }

  if ("user" in authentication && authentication.user?.id) {
    return requireSessionWorkspaceAccess(authentication, workspaceId, minPermission, requestId, instance);
  }

  const keyAuth = authentication as TAuthenticationApiKey;
  if (keyAuth.apiKeyId && Array.isArray(keyAuth.workspacePermissions)) {
    const log = logger.withContext({ requestId, workspaceId, apiKeyId: keyAuth.apiKeyId });

    try {
      const context = await resolveV3WorkspaceContext(workspaceId);
      const allowed = await can(
        { type: "apiKey", id: keyAuth.apiKeyId },
        getWorkspaceAuthorizationAction(minPermission),
        { type: "workspace", id: context.workspaceId }
      );

      if (!allowed) {
        log.warn({ statusCode: 403 }, "API key not allowed for workspace");
        return problemForbidden(requestId, "You are not authorized to access this resource", instance);
      }

      return context;
    } catch (error) {
      if (error instanceof ResourceNotFoundError) {
        log.warn({ statusCode: 403, errorCode: error.name }, "Workspace not found");
        return problemForbidden(requestId, "You are not authorized to access this resource", instance);
      }

      throw error;
    }
  }

  return problemUnauthorized(requestId, "Not authenticated", instance);
}
