import "server-only";
import { cache as reactCache } from "react";
import { prisma } from "@formbricks/database";
import { Prisma } from "@formbricks/database/prisma";
import { PrismaErrorType } from "@formbricks/database/types/error";
import { ZId, ZOptionalNumber, ZString } from "@formbricks/types/common";
import { type TIngestFlag, mergeIngestFlags } from "@formbricks/types/embedded-data-ingest";
import { DatabaseError, ResourceNotFoundError } from "@formbricks/types/errors";
import {
  TClientResponseUpdateInput,
  TResponse,
  TResponseContact,
  TResponseFilterCriteria,
  TResponseWithQuotas,
  ZClientResponseUpdateInput,
  ZResponseFilterCriteria,
} from "@formbricks/types/responses";
import { TSurvey } from "@formbricks/types/surveys/types";
import { TTag } from "@formbricks/types/tags";
import { getIsQuotasEnabled } from "@/modules/ee/license-check/lib/utils";
import { reduceQuotaLimits } from "@/modules/ee/quotas/lib/quotas";
import { requestEmailAuditErasureRequired } from "@/modules/email/lib/email-audit-maintenance";
import { deleteResponseFileUrls } from "@/modules/storage/lib/delete-response-files";
import { enqueueReplacedSignatureFileCleanup } from "@/modules/storage/lib/replaced-signature-files";
import {
  collectResponseFileUrls,
  getSurveyUploadElementIds,
  resolveStorageUrlsInObject,
} from "@/modules/storage/utils";
import { getOrganizationIdFromWorkspaceId } from "@/modules/survey/lib/organization";
import { getOrganizationBilling } from "@/modules/survey/lib/survey";
import { ITEMS_PER_PAGE } from "../constants";
import { deleteDisplay } from "../display/service";
import { getOrganization } from "../organization/service";
import { getSurvey } from "../survey/service";
import { convertToCsv, convertToXlsxBuffer } from "../utils/file-conversion";
import { validateInputs } from "../utils/validate";
import { calBookingsForAnswers } from "./cal-bookings";
import { getSurveyFilteringValues } from "./filtering-values";
import { withoutNotShownAnswers } from "./not-shown-answers";
import { TResponseCursor, ZResponseCursor, whereAfterResponseCursor } from "./pagination";
import { standardColumnGroups, standardHeaders } from "./standard-columns";
import {
  calculateTtcTotal,
  extractSurveyDetails,
  getResponsesFileName,
  getResponsesJson,
  normalizeResponseLanguage,
} from "./utils";
import { buildWhereClause } from "./where-clause";

const RESPONSES_PER_PAGE = 10;

export const responseSelection = {
  id: true,
  createdAt: true,
  updatedAt: true,
  surveyId: true,
  finished: true,
  endingId: true,
  data: true,
  meta: true,
  ttc: true,
  variables: true,
  contactAttributes: true,
  singleUseId: true,
  language: true,
  outcome: true,
  displayId: true,
  contact: {
    select: {
      id: true,
      attributes: {
        select: { attributeKey: true, value: true },
      },
    },
  },
  tags: {
    select: {
      tag: {
        select: {
          id: true,
          createdAt: true,
          updatedAt: true,
          name: true,
          workspaceId: true,
        },
      },
    },
  },
} satisfies Prisma.ResponseSelect;

export const getResponseContact = (
  responsePrisma: Prisma.ResponseGetPayload<{ select: typeof responseSelection }>
): TResponseContact | null => {
  if (!responsePrisma.contact) return null;

  return {
    id: responsePrisma.contact.id,
    userId: responsePrisma.contact.attributes.find((attribute) => attribute.attributeKey.key === "userId")
      ?.value as string,
  };
};

export const mapResponsePrismaToResponse = (
  responsePrisma: Prisma.ResponseGetPayload<{ select: typeof responseSelection }>
): TResponse => ({
  ...responsePrisma,
  contact: getResponseContact(responsePrisma),
  tags: responsePrisma.tags.map((tagPrisma: { tag: TTag }) => tagPrisma.tag),
});

/**
 * Scoped by workspace on purpose: this feeds the contact detail page, which is reached through a
 * workspace id in the URL. A contact id alone is not a tenant boundary, so the responses are
 * filtered through the workspace of the contact they belong to.
 */
export const getResponsesByContactId = reactCache(
  async (
    contactId: string,
    workspaceId: string,
    /** ENG-3282: the viewer's survey-visibility clause, applied to each response's survey. */
    visibleSurveyWhere: Prisma.SurveyWhereInput,
    page?: number
  ): Promise<TResponseWithQuotas[]> => {
    validateInputs([contactId, ZId], [workspaceId, ZId], [page, ZOptionalNumber]);

    try {
      const responsePrisma = await prisma.response.findMany({
        where: {
          contactId,
          contact: { workspaceId },
          ...(Object.keys(visibleSurveyWhere).length > 0 ? { survey: visibleSurveyWhere } : {}),
        },
        select: {
          ...responseSelection,
          // The contact page's response cards mark what the respondent was not shown (ENG-6936).
          notShown: true,
          quotaLinks: {
            where: {
              status: "screenedIn",
            },
            include: {
              quota: {
                select: {
                  id: true,
                  name: true,
                },
              },
            },
          },
        },
        take: page ? ITEMS_PER_PAGE : undefined,
        skip: page ? ITEMS_PER_PAGE * (page - 1) : undefined,
        orderBy: {
          createdAt: "desc",
        },
      });

      const responses: TResponseWithQuotas[] = [];

      await Promise.all(
        responsePrisma.map(async (response) => {
          const responseContact: TResponseContact = {
            id: response.contact?.id as string,
            userId: response.contact?.attributes.find((attribute) => attribute.attributeKey.key === "userId")
              ?.value,
          };

          responses.push({
            ...response,
            contact: responseContact,

            tags: response.tags.map((tagPrisma: { tag: TTag }) => tagPrisma.tag),
            quotas: response.quotaLinks.map((quotaLinkPrisma) => quotaLinkPrisma.quota),
          });
        })
      );

      return responses;
    } catch (error) {
      if (error instanceof Prisma.PrismaClientKnownRequestError) {
        throw new DatabaseError(error.message);
      }

      throw error;
    }
  }
);

export const getResponseBySingleUseId = reactCache(
  async (surveyId: string, singleUseId: string): Promise<TResponse | null> => {
    validateInputs([surveyId, ZId], [singleUseId, ZString]);

    try {
      const responsePrisma = await prisma.response.findUnique({
        where: {
          surveyId_singleUseId: { surveyId, singleUseId },
        },
        select: responseSelection,
      });

      if (!responsePrisma) {
        return null;
      }

      return mapResponsePrismaToResponse(responsePrisma);
    } catch (error) {
      if (error instanceof Prisma.PrismaClientKnownRequestError) {
        throw new DatabaseError(error.message);
      }

      throw error;
    }
  }
);

export const getResponse = reactCache(async (responseId: string): Promise<TResponse | null> => {
  validateInputs([responseId, ZId]);

  try {
    const responsePrisma = await prisma.response.findUnique({
      where: {
        id: responseId,
      },
      select: responseSelection,
    });

    if (!responsePrisma) {
      return null;
    }

    return mapResponsePrismaToResponse(responsePrisma);
  } catch (error) {
    if (error instanceof Prisma.PrismaClientKnownRequestError) {
      throw new DatabaseError(error.message);
    }

    throw error;
  }
});

export const getResponseWithQuotas = reactCache(
  async (responseId: string): Promise<TResponseWithQuotas | null> => {
    validateInputs([responseId, ZId]);

    try {
      const responsePrisma = await prisma.response.findUnique({
        where: {
          id: responseId,
        },
        select: {
          ...responseSelection,
          // The response card reads it to mark what the respondent was not shown (ENG-6936).
          notShown: true,
          quotaLinks: {
            where: { status: "screenedIn" },
            include: { quota: { select: { id: true, name: true } } },
          },
        },
      });

      if (!responsePrisma) {
        return null;
      }

      const { quotaLinks, ...rest } = responsePrisma;
      return {
        ...mapResponsePrismaToResponse(rest),
        quotas: quotaLinks.map((ql) => ql.quota),
      };
    } catch (error) {
      if (error instanceof Prisma.PrismaClientKnownRequestError) {
        throw new DatabaseError(error.message);
      }

      throw error;
    }
  }
);

export const getResponseSnapshotForPipeline = async (responseId: string): Promise<TResponse | null> => {
  validateInputs([responseId, ZId]);

  try {
    const responsePrisma = await prisma.response.findUnique({
      where: {
        id: responseId,
      },
      select: responseSelection,
    });

    if (!responsePrisma) {
      return null;
    }

    return mapResponsePrismaToResponse(responsePrisma);
  } catch (error) {
    if (error instanceof Prisma.PrismaClientKnownRequestError) {
      throw new DatabaseError(error.message);
    }

    throw error;
  }
};

export const getResponseFilteringValues = reactCache(async (surveyId: string) => {
  validateInputs([surveyId, ZId]);

  try {
    const survey = await getSurvey(surveyId);
    if (!survey) {
      throw new ResourceNotFoundError("Survey", surveyId);
    }

    // Distinct-value queries scoped to the survey just loaded, not a read of every response;
    // no cache, see `getSurveyFilteringValues` for the freshness and cost trade-off (ENG-3755).
    return await getSurveyFilteringValues(survey);
  } catch (error) {
    if (error instanceof Prisma.PrismaClientKnownRequestError) {
      throw new DatabaseError(error.message);
    }

    throw error;
  }
});

export const getResponses = reactCache(
  async (
    surveyId: string,
    limit?: number,
    offset?: number,
    filterCriteria?: TResponseFilterCriteria,
    cursor?: TResponseCursor,
    // The not-shown record (ENG-6936) is read only for the app's own results, never for the v1
    // management API or the standard export, which also read through here.
    options?: { withNotShown?: boolean }
  ): Promise<TResponseWithQuotas[]> => {
    validateInputs(
      [surveyId, ZId],
      [limit, ZOptionalNumber],
      [offset, ZOptionalNumber],
      [filterCriteria, ZResponseFilterCriteria.optional()],
      [cursor, ZResponseCursor.optional()]
    );

    limit = limit ?? RESPONSES_PER_PAGE;
    const survey = await getSurvey(surveyId);
    if (!survey) return [];
    try {
      const whereClause: Prisma.ResponseWhereInput = {
        surveyId,
        ...buildWhereClause(survey, filterCriteria),
      };

      const responses = await prisma.response.findMany({
        where: whereAfterResponseCursor(whereClause, cursor),
        select: {
          ...responseSelection,
          ...(options?.withNotShown && { notShown: true }),
          quotaLinks: {
            where: {
              status: "screenedIn",
            },
            include: {
              quota: {
                select: {
                  id: true,
                  name: true,
                },
              },
            },
          },
        },
        orderBy: [
          {
            createdAt: "desc",
          },
          {
            id: "desc", // Secondary sort by ID for consistent pagination
          },
        ],
        take: limit,
        skip: offset,
      });

      const transformedResponses: TResponseWithQuotas[] = responses.map((responsePrisma) => {
        const { quotaLinks, ...response } = responsePrisma;
        return {
          ...response,
          contact: getResponseContact(responsePrisma),
          tags: responsePrisma.tags.map((tagPrisma: { tag: TTag }) => tagPrisma.tag),
          quotas: quotaLinks.map((quotaLinkPrisma) => quotaLinkPrisma.quota),
        };
      });

      return transformedResponses;
    } catch (error) {
      if (error instanceof Prisma.PrismaClientKnownRequestError) {
        throw new DatabaseError(error.message);
      }

      throw error;
    }
  }
);

export const getResponseDownloadFile = async (
  surveyId: string,
  format: "csv" | "xlsx",
  filterCriteria?: TResponseFilterCriteria,
  /** Include columns groups switched off in the Export modal. None: today's file, every column. */
  excludedColumns: readonly string[] = []
): Promise<{ fileContents: string; fileName: string }> => {
  validateInputs([surveyId, ZId], [format, ZString], [filterCriteria, ZResponseFilterCriteria.optional()]);
  try {
    const survey = await getSurvey(surveyId);

    if (!survey) {
      throw new ResourceNotFoundError("Survey", surveyId);
    }

    const batchSize = 3000;

    // Use cursor-based pagination instead of count + offset to avoid expensive queries
    const responses: TResponse[] = [];
    let cursor: TResponseCursor | undefined = undefined;
    let hasMore = true;

    while (hasMore) {
      const batch = await getResponses(surveyId, batchSize, 0, filterCriteria, cursor);
      responses.push(...batch);

      const lastResponse = batch.at(-1);
      if (!lastResponse || batch.length < batchSize) {
        hasMore = false;
      } else {
        cursor = { id: lastResponse.id, createdAt: lastResponse.createdAt };
      }
    }

    const { metaDataFields, elements, hiddenFields, variables, userAttributes } = extractSurveyDetails(
      survey,
      responses
    );

    const organizationId = await getOrganizationIdFromWorkspaceId(survey.workspaceId);
    if (!organizationId) {
      throw new ResourceNotFoundError("Organization", null);
    }

    const [organizationBilling, organization] = await Promise.all([
      getOrganizationBilling(organizationId),
      getOrganization(organizationId),
    ]);

    if (!organizationBilling) {
      throw new ResourceNotFoundError("OrganizationBilling", organizationId);
    }
    const isQuotasAllowed = await getIsQuotasEnabled(organizationId);

    const headers = standardHeaders(
      standardColumnGroups({
        survey,
        details: { metaDataFields, elements, hiddenFields, variables, userAttributes },
        isQuotasAllowed,
      }),
      excludedColumns
    );

    const resolvedResponses = responses.map((r) => ({ ...r, data: resolveStorageUrlsInObject(r.data) }));
    const jsonData = getResponsesJson(
      survey,
      resolvedResponses,
      elements,
      userAttributes,
      isQuotasAllowed,
      organization?.displayTimeZone ?? "UTC"
    );

    const fileName = getResponsesFileName(survey?.name || "", format);
    let fileContents: string;

    if (format === "xlsx") {
      const buffer = convertToXlsxBuffer(headers, jsonData);
      fileContents = buffer.toString("base64");
    } else {
      fileContents = await convertToCsv(headers, jsonData);
    }

    return {
      fileContents,
      fileName,
    };
  } catch (error) {
    if (error instanceof Prisma.PrismaClientKnownRequestError) {
      throw new DatabaseError(error.message);
    }

    throw error;
  }
};

export const getResponsesByWorkspaceId = reactCache(
  async (workspaceId: string, limit?: number, offset?: number): Promise<TResponse[]> => {
    validateInputs([workspaceId, ZId], [limit, ZOptionalNumber], [offset, ZOptionalNumber]);

    try {
      const responses = await prisma.response.findMany({
        where: {
          survey: {
            workspaceId,
          },
        },
        select: responseSelection,
        orderBy: [
          {
            createdAt: "desc",
          },
        ],
        take: limit,
        skip: offset,
      });

      const transformedResponses: TResponse[] = await Promise.all(
        responses.map(async (responsePrisma) => {
          return {
            ...responsePrisma,
            contact: getResponseContact(responsePrisma),
            tags: responsePrisma.tags.map((tagPrisma: { tag: TTag }) => tagPrisma.tag),
          };
        })
      );

      return transformedResponses;
    } catch (error) {
      if (error instanceof Prisma.PrismaClientKnownRequestError) {
        throw new DatabaseError(error.message);
      }

      throw error;
    }
  }
);

/**
 * Locks a response row for the rest of `tx` and returns its `finished` flag, or `null` when the workspace has
 * no such response. Scoped through the response's survey, so a caller holding another workspace's response
 * id can neither lock nor read it. A check that guards a response write belongs on this result: under the lock, no other write can
 * commit between the check and the write, and the read in `updateResponse` that follows sees the latest
 * committed row, so its merge of `data`/`variables`/`ttc` cannot drop a concurrent update's keys.
 *
 * FOR NO KEY UPDATE rather than FOR UPDATE: the update never changes the key, and the weaker lock does not
 * conflict with the FOR KEY SHARE that inserts referencing this row take (quota links, tags, notes).
 */
export const lockResponseForUpdate = async (
  tx: Prisma.TransactionClient,
  { responseId, workspaceId }: { responseId: string; workspaceId: string }
): Promise<{ finished: boolean } | null> => {
  const [locked] = await tx.$queryRaw<{ finished: boolean }[]>`
    SELECT r."finished"
    FROM "Response" r
    JOIN "Survey" s ON s."id" = r."surveyId"
    WHERE r."id" = ${responseId} AND s."workspaceId" = ${workspaceId}
    FOR NO KEY UPDATE OF r
  `;
  return locked ?? null;
};

/**
 * `ingestFlags` is the Embedded Data ingest contract's verdict on `responseInput.data` (ENG-1845),
 * computed server-side by the caller and passed separately so it can never arrive from the client.
 *
 * Omitting it leaves the stored column untouched — the authenticated management routes update a
 * response without running the contract, and must not clear what a client ingest wrote. Passing it
 * unions by key: a key this payload rewrote takes its new verdict, including none at all, so a value
 * corrected on a later block stops being flagged.
 */

export const updateResponse = async (
  responseId: string,
  // `TResponseUpdateInput` plus the survey's not-shown record, which only the client route parses; the
  // management routes parse `ZResponseUpdateInput`, so theirs never carries one.
  responseInput: TClientResponseUpdateInput,
  tx?: Prisma.TransactionClient,
  ingestFlags?: readonly TIngestFlag[]
): Promise<TResponse> => {
  validateInputs([responseId, ZId], [responseInput, ZClientResponseUpdateInput]);
  try {
    const prismaClient = tx ?? prisma;
    // use direct prisma call to avoid cache issues
    const currentResponse = await prismaClient.response.findUnique({
      where: {
        id: responseId,
      },
      // `ingestFlags` is read here and nowhere else: it is not part of `responseSelection`, so it
      // stays off every response this module returns rather than riding along into API payloads that
      // never declared it. `calBookings` is read for the same reason: only to merge into.
      select: { ...responseSelection, ingestFlags: true, calBookings: true },
    });

    if (!currentResponse) {
      throw new ResourceNotFoundError("Response", responseId);
    }

    // merge data object. The survey sends its whole not-shown record with every update (ENG-6936,
    // ADR 0029): it replaces the stored one, and an answer to anything it lists is removed, so an item
    // that ended up hidden after Back or a changed answer keeps no stale answer.
    const data = await withoutNotShownAnswers(
      prismaClient,
      currentResponse.surveyId,
      responseInput.notShown,
      { ...currentResponse.data, ...responseInput.data }
    );
    // merge ttc object (similar to data) to preserve TTC from previous blocks
    const currentTtc = currentResponse.ttc;
    const mergedTtc = responseInput.ttc
      ? {
          ...currentTtc,
          ...responseInput.ttc,
        }
      : currentTtc;
    // Calculate total only when finished
    const ttc = responseInput.finished ? calculateTtcTotal(mergedTtc) : mergedTtc;
    // Canonicalize on write (ENG-1067), same as response creation — see normalizeResponseLanguage.
    const language = normalizeResponseLanguage(responseInput.language);
    const variables = {
      ...currentResponse.variables,
      ...responseInput.variables,
    };
    const mergedIngestFlags =
      ingestFlags === undefined
        ? undefined
        : mergeIngestFlags(currentResponse.ingestFlags ?? [], {
            data: responseInput.data ?? {},
            flags: ingestFlags,
          });
    // By Question ID, like `data`: a booking this payload carries replaces that question's stored one, and
    // the other questions' bookings stay. Nothing in the payload leaves the column untouched.
    // Bookings follow their answers: one whose answer the not-shown filter just removed goes too, even
    // when this update carries no booking of its own.
    const storedCalBookings = currentResponse.calBookings ?? {};
    const mergedCalBookings = calBookingsForAnswers(
      { ...storedCalBookings, ...responseInput.calBookings },
      data
    );
    const calBookingsChanged =
      responseInput.calBookings !== undefined ||
      Object.keys(mergedCalBookings).length !== Object.keys(storedCalBookings).length;

    const responsePrisma = await prismaClient.response.update({
      where: {
        id: responseId,
      },
      data: {
        finished: responseInput.finished,
        endingId: responseInput.endingId,
        data,
        ttc,
        language,
        variables,
        ...(responseInput.notShown !== undefined && { notShown: responseInput.notShown }),
        // Written whenever the contract ran, empty included — see `buildPrismaResponseData` for why
        // `null` has to stay reserved for "no ingest boundary has written this".
        ...(mergedIngestFlags !== undefined && { ingestFlags: mergedIngestFlags }),
        ...(calBookingsChanged && { calBookings: mergedCalBookings }),
      },
      select: responseSelection,
    });

    // After the write, on the same client: in the callers' transaction a failed update queues nothing,
    // and a failed queueing rolls the update back, as for a delete. `currentResponse` is the row this
    // update read, so a signature it replaces is compared against what was really stored.
    if (responseInput.data) {
      await enqueueReplacedSignatureFileCleanup(
        prismaClient,
        { surveyId: currentResponse.surveyId, previousData: currentResponse.data, nextData: data },
        { bestEffort: !tx }
      );
    }

    const response: TResponse = {
      ...responsePrisma,
      contact: getResponseContact(responsePrisma),
      tags: responsePrisma.tags.map((tagPrisma: { tag: TTag }) => tagPrisma.tag),
    };

    return response;
  } catch (error) {
    if (error instanceof Prisma.PrismaClientKnownRequestError) {
      if (
        error.code === PrismaErrorType.RelatedRecordNotFound ||
        error.code === PrismaErrorType.RecordNotFound
      ) {
        throw new ResourceNotFoundError("Response", responseId);
      }

      throw new DatabaseError(error.message);
    }

    throw error;
  }
};

const findAndDeleteUploadedFilesInResponse = async (response: TResponse, survey: TSurvey): Promise<void> => {
  const fileUrls = collectResponseFileUrls(response.data, getSurveyUploadElementIds(survey), survey.id);

  await deleteResponseFileUrls(fileUrls, survey.workspaceId);
};

export const deleteResponse = async (
  responseId: string,
  decrementQuotas: boolean = false
): Promise<TResponse> => {
  validateInputs([responseId, ZId]);
  try {
    const txResponse = await prisma.$transaction(async (tx) => {
      const responsePrisma = await tx.response.delete({
        where: {
          id: responseId,
        },
        select: {
          ...responseSelection,
          quotaLinks: {
            where: {
              status: "screenedIn",
            },
            include: {
              quota: {
                select: {
                  id: true,
                },
              },
            },
          },
        },
      });

      const { quotaLinks, ...responseWithoutQuotas } = responsePrisma;

      const response: TResponse = {
        ...responseWithoutQuotas,
        contact: getResponseContact(responsePrisma),
        tags: responseWithoutQuotas.tags.map((tagPrisma: { tag: TTag }) => tagPrisma.tag),
      };

      if (response.displayId) {
        await deleteDisplay(response.displayId, tx);
      }

      if (decrementQuotas) {
        const quotaIds = quotaLinks?.map((link) => link.quota.id) ?? [];
        await reduceQuotaLimits(quotaIds, tx);
      }

      await requestEmailAuditErasureRequired({ responseId }, tx);

      return response;
    });

    const survey = await getSurvey(txResponse.surveyId);

    if (survey) {
      await findAndDeleteUploadedFilesInResponse(txResponse, survey);
    }

    return txResponse;
  } catch (error) {
    if (error instanceof Prisma.PrismaClientKnownRequestError) {
      throw new DatabaseError(error.message);
    }

    throw error;
  }
};

export const getResponseCountBySurveyId = reactCache(
  async (surveyId: string, filterCriteria?: TResponseFilterCriteria): Promise<number> => {
    validateInputs([surveyId, ZId], [filterCriteria, ZResponseFilterCriteria.optional()]);

    try {
      const survey = await getSurvey(surveyId);
      if (!survey) return 0;

      const responseCount = await prisma.response.count({
        where: {
          surveyId: surveyId,
          ...buildWhereClause(survey, filterCriteria),
        },
      });
      return responseCount;
    } catch (error) {
      if (error instanceof Prisma.PrismaClientKnownRequestError) {
        throw new DatabaseError(error.message);
      }

      throw error;
    }
  }
);
