import { z } from "zod";
import { type TResponseFilterCriteria, ZResponseFilterCriteriaFromJson } from "@formbricks/types/responses";
import { withV3ApiWrapper } from "@/app/api/v3/lib/api-wrapper";
import {
  problemBadRequest,
  problemTooManyRequests,
  problemUnprocessableContent,
  successResponse,
} from "@/app/api/v3/lib/response";
import { getAuthorizedV3Survey } from "@/app/api/v3/surveys/authorization";
import { getSessionUserId } from "@/app/api/v3/surveys/lib/operations";
import { getOrganization } from "@/lib/organization/service";
import { capturePostHogEvent } from "@/lib/posthog";
import { checkRateLimit } from "@/modules/core/rate-limit/rate-limit";
import { rateLimitConfigs } from "@/modules/core/rate-limit/rate-limit-configs";
import { MAX_ATTACHMENT_FILES } from "@/modules/storage/attachment-export/constants";
import { streamAttachmentsAsZip } from "@/modules/storage/attachment-export/export-attachments";
import { collectResponseAttachments } from "@/modules/storage/lib/collect-response-attachments";

/**
 * `GET /api/surveys/{surveyId}/attachments` — the response-attachment ZIP export (ENG-1256).
 *
 * Lives under `(internal)` rather than `/api/v3` because it carries no OpenAPI entry and makes no
 * compatibility promise: a streaming ZIP has no JSON response schema for the contract suite to match,
 * and the only caller is this app's own responses table. Session-only — the browser reaches it by
 * navigating, so the cookie is the credential.
 *
 * It still goes through `withV3ApiWrapper`, which is where request validation, rate limiting and audit
 * logging live; the wrapper is a shared utility, not part of the public surface.
 *
 * `dryRun=true` returns the counts as JSON instead of the archive. The client needs that because the
 * download is a plain navigation: once the 200 and its headers are flushed there is no way back to a
 * 4xx, and rendering a problem document would replace the responses table the user is looking at. So
 * the client asks first, toasts on empty or over-cap, and only then navigates.
 */

const paramsSchema = z.object({
  surveyId: z.cuid2(),
});

const querySchema = z.object({
  /**
   * The response filter, JSON-encoded, matching what the CSV/Excel export sends. A GET carries it in the
   * query string, which is why selecting individual responses is not supported here — a few hundred
   * response ids would blow past the ~8 KB a proxy accepts in a request line.
   */
  filters: z.string().optional(),
  dryRun: z
    .enum(["true", "false"])
    .optional()
    .transform((value) => value === "true"),
});

/** The `filters` query parameter as a response filter, or the 400 that refuses it. */
const parseFilterCriteria = (
  filters: string | undefined,
  requestId: string,
  instance: string | undefined
): TResponseFilterCriteria | undefined | Response => {
  if (!filters) return undefined;
  let parsed: unknown;
  try {
    parsed = JSON.parse(filters);
  } catch {
    return problemBadRequest(requestId, "The `filters` parameter is not valid JSON.", {
      instance,
      invalid_params: [{ name: "filters", reason: "Expected a JSON-encoded response filter." }],
    });
  }

  const validation = ZResponseFilterCriteriaFromJson.safeParse(parsed);
  if (!validation.success) {
    return problemBadRequest(requestId, "The `filters` parameter is not a valid response filter.", {
      instance,
      invalid_params: [{ name: "filters", reason: validation.error.issues[0]?.message ?? "Invalid" }],
    });
  }
  return validation.data;
};

export const GET = withV3ApiWrapper({
  auth: "session",
  action: "exported",
  targetType: "file",
  schemas: {
    params: paramsSchema,
    query: querySchema,
  },
  handler: async ({ parsedInput, authentication, requestId, instance, auditLog }) => {
    const { surveyId } = parsedInput.params;
    const { filters, dryRun } = parsedInput.query;

    const { survey, authResult, response } = await getAuthorizedV3Survey({
      surveyId,
      authentication,
      access: "read",
      requestId,
      instance,
    });

    if (response) return response;

    const parsedFilters = parseFilterCriteria(filters, requestId, instance);
    if (parsedFilters instanceof Response) return parsedFilters;
    const filterCriteria = parsedFilters;

    // One pass serves both branches: the pre-flight needs the counts, the download needs the entries,
    // and the collector never opens a storage stream so there is nothing to waste by holding them.
    // The folders are stamped in the org's display time zone, so an archive and the CSV export of the
    // same responses read the same clock.
    const organization = await getOrganization(authResult.organizationId);

    const { entries, fileCount, responseCount, exceedsMaxFiles } = await collectResponseAttachments({
      survey,
      filterCriteria,
      maxFiles: MAX_ATTACHMENT_FILES,
      timeZone: organization?.displayTimeZone ?? "UTC",
    });

    if (dryRun) {
      // The wrapper stamps every request on this route as `exported`, which is reserved for data that
      // actually leaves the product as files. A pre-flight reads counts and streams nothing, so it is
      // recorded as a query instead of a phantom export.
      if (auditLog) {
        auditLog.action = "queried";
        auditLog.organizationId = authResult.organizationId;
        auditLog.targetId = survey.id;
      }

      return successResponse(
        { fileCount, responseCount, exceedsMaxFiles, maxFiles: MAX_ATTACHMENT_FILES },
        { requestId }
      );
    }

    if (exceedsMaxFiles) {
      return problemUnprocessableContent(
        requestId,
        `This export holds more than ${MAX_ATTACHMENT_FILES} files. Narrow the response filter and try again.`,
        { instance, code: "attachment_export_too_large" }
      );
    }

    if (fileCount === 0) {
      return problemUnprocessableContent(requestId, "There are no attachments to export.", {
        instance,
        code: "attachment_export_empty",
      });
    }

    const sessionUserId = getSessionUserId(authentication);

    // Charged here rather than through the wrapper's `customRateLimitConfig`: the wrapper runs before
    // the handler knows whether this is a download or the client's cheap dryRun pre-flight, so a budget
    // applied there would spend a download's allowance on a pre-flight. Pre-flights are still bounded by
    // the wrapper's default API limit. `checkRateLimit` rather than `applyRateLimit` because the wrapper
    // turns a thrown error into a 500, and this has to be a 429.
    if (sessionUserId) {
      const limit = await checkRateLimit(rateLimitConfigs.storage.attachmentsExport, sessionUserId);
      if (limit.ok && !limit.data.allowed) {
        return problemTooManyRequests(
          requestId,
          "Too many attachment exports. Try again shortly.",
          limit.data.retryAfter
        );
      }
    }

    if (auditLog) {
      auditLog.organizationId = authResult.organizationId;
      auditLog.targetId = survey.id;
    }

    if (sessionUserId) {
      capturePostHogEvent(
        sessionUserId,
        "attachments_exported",
        {
          survey_id: survey.id,
          file_count: fileCount,
          response_count: responseCount,
          filter_applied: Boolean(filterCriteria),
          organization_id: authResult.organizationId,
          workspace_id: authResult.workspaceId,
        },
        { organizationId: authResult.organizationId, workspaceId: authResult.workspaceId }
      );
    }

    return streamAttachmentsAsZip({ entries, survey, now: new Date() });
  },
});
