import { NextResponse } from "next/server";
import { logger } from "@formbricks/logger";
import {
  AuthenticationError,
  AuthorizationError,
  InvalidInputError,
  ResourceNotFoundError,
} from "@formbricks/types/errors";
import { RequestBodyTooLargeError, parseFormDataWithLimit } from "@/app/lib/api/request-body";
import { assertCan } from "@/lib/authorization";
import { assertFeedbackSourceDirectoryAccess } from "@/lib/feedback-source/access";
import { CsvImportValidationError, importCsvFile } from "@/lib/feedback-source/csv-file-import";
import { getFeedbackSourceWithMappingsById } from "@/lib/feedback-source/service";
import { getUser } from "@/lib/user/service";
import { getSession } from "@/modules/auth/lib/session";
import {
  CSV_FILE_TOO_LARGE_ERROR_CODE,
  CSV_IMPORT_FAILED_ERROR_CODE,
  MAX_CSV_VALUES,
} from "@/modules/ee/unify-feedback/sources/types";

const CSV_IMPORT_REQUEST_BODY_LIMIT = MAX_CSV_VALUES.FILE_SIZE + 1024 * 1024;

const getContentLength = (headers: Headers): number | null => {
  const contentLength = headers.get("content-length");
  if (!contentLength) return null;

  const parsed = Number(contentLength);
  return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : null;
};

const getStringFormValue = (formData: FormData, key: string): string | null => {
  const value = formData.get(key);
  return typeof value === "string" && value.trim() !== "" ? value : null;
};

const getCsvFile = (formData: FormData): File | null => {
  const file = formData.get("file");
  return file instanceof File ? file : null;
};

const buildCsvImportErrorResponse = (
  error: string,
  status: number,
  details: { row?: number; max?: number } = {}
) => NextResponse.json({ error, ...details }, { status });

/** The signed-in user, or the authentication or authorization error the route maps to 401 or 403. */
const getSessionUser = async () => {
  const session = await getSession();
  if (!session?.user) {
    throw new AuthenticationError("Not authenticated");
  }

  const user = await getUser(session.user.id);
  if (!user) {
    throw new AuthorizationError("User not found");
  }
  return user;
};

/** The error response for a failed import: the known refusals by status, anything else as a 500. */
const toCsvImportErrorResponse = (error: unknown) => {
  if (error instanceof CsvImportValidationError) {
    return buildCsvImportErrorResponse(error.code, error.code === CSV_FILE_TOO_LARGE_ERROR_CODE ? 413 : 400, {
      row: error.row,
      max: error.max,
    });
  }

  if (error instanceof AuthenticationError) {
    return buildCsvImportErrorResponse(error.message, 401);
  }

  if (error instanceof AuthorizationError) {
    return buildCsvImportErrorResponse(error.message, 403);
  }

  if (error instanceof InvalidInputError || error instanceof ResourceNotFoundError) {
    return buildCsvImportErrorResponse(error.message, 400);
  }

  logger.error(
    { errorName: error instanceof Error ? error.name : "unknown" },
    "Failed to import CSV feedback source data"
  );
  return buildCsvImportErrorResponse(CSV_IMPORT_FAILED_ERROR_CODE, 500);
};

export const POST = async (request: Request) => {
  try {
    const contentLength = getContentLength(request.headers);
    if (contentLength !== null && contentLength > CSV_IMPORT_REQUEST_BODY_LIMIT) {
      return buildCsvImportErrorResponse(CSV_FILE_TOO_LARGE_ERROR_CODE, 413, {
        max: MAX_CSV_VALUES.FILE_SIZE,
      });
    }

    const user = await getSessionUser();

    // Bounded while reading, not just by the header above: a chunked upload carries no Content-Length, and
    // the patched Next no longer cuts any body off for us (ENG-3972).
    let formData: FormData;
    try {
      formData = await parseFormDataWithLimit(request, CSV_IMPORT_REQUEST_BODY_LIMIT);
    } catch (error) {
      if (error instanceof RequestBodyTooLargeError) {
        return buildCsvImportErrorResponse(CSV_FILE_TOO_LARGE_ERROR_CODE, 413, {
          max: MAX_CSV_VALUES.FILE_SIZE,
        });
      }
      throw new InvalidInputError("Malformed form data");
    }

    const workspaceId = getStringFormValue(formData, "workspaceId");
    const feedbackSourceId = getStringFormValue(formData, "feedbackSourceId");
    const file = getCsvFile(formData);

    if (!workspaceId || !feedbackSourceId || !file) {
      throw new InvalidInputError("workspaceId, feedbackSourceId, and file are required");
    }

    await assertCan({ type: "user", id: user.id }, "workspace.write", { type: "workspace", id: workspaceId });

    const feedbackSource = await getFeedbackSourceWithMappingsById(feedbackSourceId, workspaceId);
    if (!feedbackSource) {
      throw new ResourceNotFoundError("FeedbackSource", feedbackSourceId);
    }
    await assertFeedbackSourceDirectoryAccess(
      user.id,
      feedbackSource.feedbackDirectoryId,
      workspaceId,
      "write"
    );

    const result = await importCsvFile({ feedbackSourceId, workspaceId, file });

    return NextResponse.json(result);
  } catch (error) {
    return toCsvImportErrorResponse(error);
  }
};
