import { logger } from "@formbricks/logger";
import {
  TIntegrationSlackConfig,
  TIntegrationSlackConfigData,
  TIntegrationSlackCredential,
} from "@formbricks/types/integration/slack";
import { responses } from "@/app/lib/api/response";
import { withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
import { SLACK_CLIENT_ID, SLACK_CLIENT_SECRET, SLACK_REDIRECT_URI, WEBAPP_URL } from "@/lib/constants";
import { createOrUpdateIntegration, getIntegrationByType } from "@/lib/integration/service";
import {
  IntegrationOAuthStateError,
  consumeIntegrationOAuthState,
  getSafeOAuthCallbackError,
} from "@/lib/oauth/integration-state";
import { capturePostHogEvent } from "@/lib/posthog";
import { getOrganizationIdFromWorkspaceId } from "@/lib/utils/helper";
import { canUserWriteWorkspaceIntegrations } from "@/lib/workspace/auth";

/**
 * The callback's verified context: the workspace its OAuth state names (which the user may write
 * integrations to), the authorization code and the page to return to. Or the response that ends the
 * callback: a bad state or code, no access, or the provider's error sent back to that page.
 */
const resolveOAuthCallback = async (
  req: Request,
  userId: string
): Promise<{ response: Response } | { workspaceId: string; code: string | null; redirectUrl: URL }> => {
  const url = req.url;
  const queryParams = new URLSearchParams(url.split("?")[1]); // Split the URL and get the query parameters
  const state = queryParams.get("state");
  const code = queryParams.get("code");
  const error = queryParams.get("error");

  let oauthState;
  try {
    oauthState = await consumeIntegrationOAuthState({
      provider: "slack",
      userId: userId,
      state,
    });
  } catch (err) {
    if (err instanceof IntegrationOAuthStateError) {
      return {
        response: responses.badRequestResponse("Invalid OAuth state"),
      };
    }

    throw err;
  }

  const workspaceId = oauthState.workspaceId;
  if (!workspaceId) {
    return {
      response: responses.badRequestResponse("Invalid workspaceId"),
    };
  }

  const canUserAccessWorkspace = await canUserWriteWorkspaceIntegrations(userId, workspaceId);
  if (!canUserAccessWorkspace) {
    return {
      response: responses.unauthorizedResponse(),
    };
  }

  const basePath = `/workspaces/${workspaceId}/settings/workspace`;
  const redirectUrl = new URL(`${basePath}/integrations/slack`, WEBAPP_URL);
  const safeError = getSafeOAuthCallbackError(error);

  if (code && typeof code !== "string") {
    return {
      response: responses.badRequestResponse("`code` must be a string"),
    };
  }

  if (!code && safeError) {
    redirectUrl.searchParams.set("error", safeError);
    return {
      response: Response.redirect(redirectUrl),
    };
  }

  return { workspaceId, code, redirectUrl };
};

export const GET = withV1ApiWrapper({
  handler: async ({ req, authentication }) => {
    if (!authentication || !("user" in authentication)) {
      return { response: responses.notAuthenticatedResponse() };
    }

    const callback = await resolveOAuthCallback(req, authentication.user.id);
    if ("response" in callback) return callback;
    const { workspaceId, code, redirectUrl } = callback;

    if (!SLACK_CLIENT_ID)
      return {
        response: responses.internalServerErrorResponse("Slack client id is missing"),
      };
    if (!SLACK_CLIENT_SECRET)
      return {
        response: responses.internalServerErrorResponse("Slack client secret is missing"),
      };

    const formData = {
      code,
      client_id: SLACK_CLIENT_ID,
      client_secret: SLACK_CLIENT_SECRET,
      redirect_uri: SLACK_REDIRECT_URI,
    };
    const formBody: string[] = [];
    for (const property in formData) {
      const encodedKey = encodeURIComponent(property);
      const encodedValue = encodeURIComponent((formData as Record<string, string>)[property]);
      formBody.push(encodedKey + "=" + encodedValue);
    }
    const bodyString = formBody.join("&");
    if (code) {
      const response = await fetch("https://slack.com/api/oauth.v2.access", {
        method: "POST",
        body: bodyString,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      });

      const data = await response.json();

      if (!data.ok) {
        return {
          response: responses.badRequestResponse(data.error),
        };
      }

      const slackCredentials: TIntegrationSlackCredential = {
        app_id: data.app_id,
        authed_user: data.authed_user,
        token_type: data.token_type,
        access_token: data.access_token,
        bot_user_id: data.bot_user_id,
        team: data.team,
      };

      const slackIntegration = await getIntegrationByType(workspaceId, "slack");

      const slackConfiguration: TIntegrationSlackConfig = {
        data: (slackIntegration?.config.data as TIntegrationSlackConfigData[]) ?? [],
        key: slackCredentials,
      };

      const integration = {
        type: "slack" as const,
        config: slackConfiguration,
      };

      const result = await createOrUpdateIntegration(workspaceId, integration);

      if (result) {
        try {
          const organizationId = await getOrganizationIdFromWorkspaceId(workspaceId);
          capturePostHogEvent(
            authentication.user.id,
            "integration_connected",
            {
              integration_type: "slack",
              organization_id: organizationId,
              workspace_id: workspaceId,
            },
            { organizationId, workspaceId }
          );
        } catch (err) {
          logger.error({ error: err }, "Failed to capture PostHog integration_connected event for slack");
        }

        return {
          response: Response.redirect(redirectUrl),
        };
      }
    }

    return {
      response: responses.badRequestResponse("Missing code or error parameter"),
    };
  },
});
