import { logger } from "@formbricks/logger";
import { getComputedEmbeddedFields, getIngestedStorageKeys } from "@formbricks/types/embedded-data-resolver";
import { Result } from "@formbricks/types/error-handlers";
import { TIntegration, TIntegrationType } from "@formbricks/types/integration";
import { TIntegrationAirtable } from "@formbricks/types/integration/airtable";
import { TIntegrationGoogleSheets } from "@formbricks/types/integration/google-sheet";
import { TIntegrationNotion, TIntegrationNotionConfigData } from "@formbricks/types/integration/notion";
import { TIntegrationSlack } from "@formbricks/types/integration/slack";
import { TResponse, TResponseDataValue, TResponseMeta } from "@formbricks/types/responses";
import { TSurveyElementTypeEnum } from "@formbricks/types/surveys/elements";
import { TSurvey } from "@formbricks/types/surveys/types";
import { getTextContent } from "@formbricks/types/surveys/validation";
import { writeData as airtableWriteData } from "@/lib/airtable/service";
import { NOTION_RICH_TEXT_LIMIT } from "@/lib/constants";
import { writeData } from "@/lib/googleSheet/service";
import { getLocalizedValue } from "@/lib/i18n/utils";
import { writeData as writeNotionData } from "@/lib/notion/service";
import { processResponseData } from "@/lib/responses";
import { writeDataToSlack } from "@/lib/slack/service";
import { getElementsFromBlocks } from "@/lib/survey/utils";
import { buildServerEmbeddedValues } from "@/lib/surveyLogic/utils";
import { getFormattedDateTimeString } from "@/lib/utils/datetime";
import { parseRecallInfo } from "@/lib/utils/recall";
import { truncateText } from "@/lib/utils/strings";
import { resolveStorageUrlAuto } from "@/modules/storage/utils";

type TIntegrationPipelineData = {
  // Widened from five keys to cover `TEmbeddedValueResponse` (ENG-2538): the Slack path resolves
  // reserved recall values off the response, and the caller already hands us a whole
  // `ZResponsePipelineJobResponse`, so this pick was under-declaring what is really there rather than
  // guarding anything.
  response: Pick<
    TResponse,
    | "id"
    | "surveyId"
    | "createdAt"
    | "updatedAt"
    | "finished"
    | "language"
    | "data"
    | "meta"
    | "variables"
    | "ttc"
    | "contactAttributes"
  >;
  surveyId: string;
};
// `hiddenFields` / `variables` stay in the pick as the resolver's fallback; `embeddedFields` carries
// the joined EmbeddedData rows the definitions are resolved through (ENG-1837).
type TPipelineIntegrationSurvey = Pick<
  TSurvey,
  "blocks" | "hiddenFields" | "variables" | "embeddedFields" | "name"
>;

const NOTION_PERSON_ATTRIBUTE_PREFIX = "person.";

const convertMetaObjectToString = (metadata: TResponseMeta): string => {
  const result: string[] = [];
  if (metadata.source) result.push(`Source: ${metadata.source}`);
  if (metadata.url) result.push(`URL: ${metadata.url}`);
  if (metadata.userAgent?.browser) result.push(`Browser: ${metadata.userAgent.browser}`);
  if (metadata.userAgent?.os) result.push(`OS: ${metadata.userAgent.os}`);
  if (metadata.userAgent?.device) result.push(`Device: ${metadata.userAgent.device}`);
  if (metadata.country) result.push(`Country: ${metadata.country}`);
  if (metadata.action) result.push(`Action: ${metadata.action}`);
  if (metadata.ipAddress) result.push(`IP Address: ${metadata.ipAddress}`);

  // Join all the elements in the result array with a newline for formatting
  return result.join("\n");
};

interface TIntegrationFieldSelection {
  elementIds: string[];
  includeCreatedAt: boolean;
  includeHiddenFields: boolean;
  includeMetadata: boolean;
  includeVariables: boolean;
  includeContactAttributes: boolean;
}

const toIntegrationFieldSelection = (config: {
  elementIds: string[];
  includeCreatedAt?: boolean | null;
  includeHiddenFields?: boolean | null;
  includeMetadata?: boolean | null;
  includeVariables?: boolean | null;
  includeContactAttributes?: boolean | null;
}): TIntegrationFieldSelection => ({
  elementIds: config.elementIds,
  includeCreatedAt: Boolean(config.includeCreatedAt),
  includeHiddenFields: Boolean(config.includeHiddenFields),
  includeMetadata: Boolean(config.includeMetadata),
  includeVariables: Boolean(config.includeVariables),
  includeContactAttributes: Boolean(config.includeContactAttributes),
});

const processDataForIntegration = async (
  integrationType: TIntegrationType,
  data: TIntegrationPipelineData,
  survey: TPipelineIntegrationSurvey,
  selection: TIntegrationFieldSelection,
  displayTimeZone: string = "UTC"
): Promise<{
  responses: string[];
  elements: string[];
}> => {
  const {
    elementIds,
    includeCreatedAt,
    includeHiddenFields,
    includeMetadata,
    includeVariables,
    includeContactAttributes,
  } = selection;
  const ingestedStorageKeys = getIngestedStorageKeys(survey);
  const ids = includeHiddenFields ? [...elementIds, ...ingestedStorageKeys] : elementIds;
  const { responses, elements } = await extractResponses(integrationType, data, ids, survey);

  if (includeMetadata) {
    responses.push(convertMetaObjectToString(data.response.meta));
    elements.push("Metadata");
  }
  if (includeVariables) {
    // The raw slot, uncoerced and with no default substituted — a response that never captured this
    // field is skipped rather than exported with a value that run never produced.
    getComputedEmbeddedFields(survey).forEach(({ field, link }) => {
      const value = data.response.variables[link.storageKey];
      if (value !== undefined) {
        responses.push(String(value));
        elements.push(field.name);
      }
    });
  }
  if (includeCreatedAt) {
    const date = new Date(data.response.createdAt);
    responses.push(`${getFormattedDateTimeString(date, displayTimeZone)}`);
    elements.push("Created At");
  }
  if (includeContactAttributes && data.response.contactAttributes) {
    Object.entries(data.response.contactAttributes).forEach(([key, value]) => {
      responses.push(String(value));
      elements.push(`person.${key}`);
    });
  }

  return {
    responses,
    elements,
  };
};

export const handleIntegrations = async (
  integrations: TIntegration[],
  data: TIntegrationPipelineData,
  survey: TPipelineIntegrationSurvey,
  displayTimeZone: string = "UTC"
) => {
  for (const integration of integrations) {
    switch (integration.type) {
      case "googleSheets": {
        const googleResult = await handleGoogleSheetsIntegration(
          integration as TIntegrationGoogleSheets,
          data,
          survey,
          displayTimeZone
        );
        if (!googleResult.ok) {
          logger.error(googleResult.error, "Error in google sheets integration");
        }
        break;
      }
      case "slack": {
        const slackResult = await handleSlackIntegration(
          integration as TIntegrationSlack,
          data,
          survey,
          displayTimeZone
        );
        if (!slackResult.ok) {
          logger.error(slackResult.error, "Error in slack integration");
        }
        break;
      }
      case "airtable": {
        const airtableResult = await handleAirtableIntegration(
          integration as TIntegrationAirtable,
          data,
          survey,
          displayTimeZone
        );
        if (!airtableResult.ok) {
          logger.error(airtableResult.error, "Error in airtable integration");
        }
        break;
      }
      case "notion": {
        const notionResult = await handleNotionIntegration(integration as TIntegrationNotion, data, survey);
        if (!notionResult.ok) {
          logger.error(notionResult.error, "Error in notion integration");
        }
        break;
      }
    }
  }
};

const handleAirtableIntegration = async (
  integration: TIntegrationAirtable,
  data: TIntegrationPipelineData,
  survey: TPipelineIntegrationSurvey,
  displayTimeZone: string
): Promise<Result<void>> => {
  try {
    if (integration.config.data.length > 0) {
      for (const element of integration.config.data) {
        if (element.surveyId === data.surveyId) {
          const values = await processDataForIntegration(
            "airtable",
            data,
            survey,
            toIntegrationFieldSelection(element),
            displayTimeZone
          );
          await airtableWriteData(integration.config.key, element, values.responses, values.elements);
        }
      }
    }

    return {
      ok: true,
      data: undefined,
    };
  } catch (err) {
    return {
      ok: false,
      error: err instanceof Error ? err : new Error(String(err)),
    };
  }
};

const handleGoogleSheetsIntegration = async (
  integration: TIntegrationGoogleSheets,
  data: TIntegrationPipelineData,
  survey: TPipelineIntegrationSurvey,
  displayTimeZone: string
): Promise<Result<void>> => {
  try {
    if (integration.config.data.length > 0) {
      for (const element of integration.config.data) {
        if (element.surveyId === data.surveyId) {
          const values = await processDataForIntegration(
            "googleSheets",
            data,
            survey,
            toIntegrationFieldSelection(element),
            displayTimeZone
          );
          const integrationData = structuredClone(integration);
          integrationData.config.data.forEach((data) => {
            data.createdAt = new Date(data.createdAt);
          });

          await writeData(integrationData, element.spreadsheetId, values.responses, values.elements);
        }
      }
    }

    return {
      ok: true,
      data: undefined,
    };
  } catch (err) {
    return {
      ok: false,
      error: err instanceof Error ? err : new Error(String(err)),
    };
  }
};

const handleSlackIntegration = async (
  integration: TIntegrationSlack,
  data: TIntegrationPipelineData,
  survey: TPipelineIntegrationSurvey,
  displayTimeZone: string
): Promise<Result<void>> => {
  try {
    if (integration.config.data.length > 0) {
      for (const element of integration.config.data) {
        if (element.surveyId === data.surveyId) {
          const values = await processDataForIntegration(
            "slack",
            data,
            survey,
            toIntegrationFieldSelection(element),
            displayTimeZone
          );
          await writeDataToSlack(
            integration.config.key,
            element.channelId,
            values.responses,
            values.elements,
            survey?.name
          );
        }
      }
    }

    return {
      ok: true,
      data: undefined,
    };
  } catch (err) {
    return {
      ok: false,
      error: err instanceof Error ? err : new Error(String(err)),
    };
  }
};

// Helper to process a single element's response for integrations
const processElementResponse = (
  element: ReturnType<typeof getElementsFromBlocks>[number],
  responseValue: TResponseDataValue
): string => {
  if (responseValue === undefined) {
    return "";
  }

  if (element.type === TSurveyElementTypeEnum.PictureSelection) {
    const selectedChoiceIds = responseValue as string[];
    return element.choices
      .filter((choice) => selectedChoiceIds.includes(choice.id))
      .map((choice) => resolveStorageUrlAuto(choice.imageUrl))
      .join("\n");
  }

  if (element.type === TSurveyElementTypeEnum.FileUpload && Array.isArray(responseValue)) {
    return responseValue
      .map((url) => (typeof url === "string" ? resolveStorageUrlAuto(url) : url))
      .join("; ");
  }

  // One stored URL string (ADR 0023), resolved to an absolute URL like a File upload's entries.
  if (element.type === TSurveyElementTypeEnum.Signature && typeof responseValue === "string") {
    return resolveStorageUrlAuto(responseValue);
  }

  return processResponseData(responseValue);
};

// Helper to create empty response object for non-slack integrations
const createEmptyResponseObject = (responseData: Record<string, unknown>): Record<string, string> => {
  return Object.keys(responseData).reduce(
    (acc, key) => {
      acc[key] = "";
      return acc;
    },
    {} as Record<string, string>
  );
};

const extractResponses = async (
  integrationType: TIntegrationType,
  pipelineData: TIntegrationPipelineData,
  elementIds: string[],
  survey: TPipelineIntegrationSurvey
): Promise<{
  responses: string[];
  elements: string[];
}> => {
  const responses: string[] = [];
  const elements: string[] = [];
  const surveyElements = getElementsFromBlocks(survey.blocks);
  const emptyResponseObject = createEmptyResponseObject(pipelineData.response.data);

  const ingestedStorageKeys = getIngestedStorageKeys(survey);

  // Slack posts one message per response, so its labels are per-response text and recall is
  // interpolated for real — including reserved fields, which used to render their fallback here
  // (ENG-2538). Every other integration writes `elements` as the SHEET/TABLE HEADER, which has to
  // read identically for every response, so the empty object stays: a header that interpolated this
  // response's answers would rename the column on every write. Reserved values are per response too,
  // so they belong on the Slack side only.
  //
  // Hoisted alongside `emptyResponseObject` because neither depends on the element: built inside the
  // loop this re-projected the whole catalog and re-walked `survey.blocks` once per element, per
  // response.
  const responseDataForRecall =
    integrationType === "slack"
      ? buildServerEmbeddedValues(pipelineData.response, survey)
      : emptyResponseObject;
  const variablesForRecall = integrationType === "slack" ? pipelineData.response.variables : {};

  for (const elementId of elementIds) {
    // Check for ingested (hidden) field storage keys
    if (ingestedStorageKeys.includes(elementId)) {
      responses.push(processResponseData(pipelineData.response.data[elementId]));
      // Labelled by storage key, while a computed field above is labelled by `field.name`. The
      // asymmetry is deliberate: a computed field's storage key is an opaque cuid, whereas an
      // ingested field's storage key IS its name today (`toDesiredEmbeddedFields` sets both to the
      // hidden field id), so the two spellings are still identical here. They diverge once the
      // shared library lands (ENG-1851), and these columns then keep showing the key — relabelling
      // is its own ticket, because `elements` IS the spreadsheet/Airtable column header and moving
      // it would silently re-header every already-configured integration, so it needs a migration
      // for existing mappings.
      //
      // The Notion picker moved to the name in ENG-3233 and does not force this side to follow: it
      // labels by name but still keys its saved mapping on `link.storageKey`, which is the
      // `element.id` `buildNotionPayloadProperties` reads each value from.
      elements.push(elementId);
      continue;
    }

    const element = surveyElements.find((q) => q.id === elementId);
    if (!element) {
      continue;
    }

    const responseValue = pipelineData.response.data[elementId];
    responses.push(processElementResponse(element, responseValue));

    elements.push(
      parseRecallInfo(
        getTextContent(getLocalizedValue(element.headline, "default")),
        responseDataForRecall,
        variablesForRecall
      ) || ""
    );
  }

  return { responses, elements };
};

const handleNotionIntegration = async (
  integration: TIntegrationNotion,
  data: TIntegrationPipelineData,
  surveyData: TPipelineIntegrationSurvey
): Promise<Result<void>> => {
  try {
    if (integration.config.data.length > 0) {
      for (const element of integration.config.data) {
        if (element.surveyId === data.surveyId) {
          const properties = buildNotionPayloadProperties(element.mapping, data, surveyData);
          await writeNotionData(element.databaseId, properties, integration.config);
        }
      }
    }

    return {
      ok: true,
      data: undefined,
    };
  } catch (err) {
    return {
      ok: false,
      error: err instanceof Error ? err : new Error(String(err)),
    };
  }
};

const buildNotionPayloadProperties = (
  mapping: TIntegrationNotionConfigData["mapping"],
  data: TIntegrationPipelineData,
  surveyData: TPipelineIntegrationSurvey
) => {
  const properties: Record<string, object> = {};
  const normalizedResponses = { ...data.response.data };

  const surveyElements = getElementsFromBlocks(surveyData.blocks);
  const surveyElementsById = new Map(surveyElements.map((element) => [element.id, element] as const));
  const pictureSelectionElementIds = new Set(
    mapping.filter((m) => m.element.type === TSurveyElementTypeEnum.PictureSelection).map((m) => m.element.id)
  );

  Object.keys(normalizedResponses).forEach((responseKey) => {
    if (!pictureSelectionElementIds.has(responseKey)) {
      return;
    }

    const selectedChoiceIds = normalizedResponses[responseKey];
    if (!Array.isArray(selectedChoiceIds)) {
      return;
    }

    const pictureElement = surveyElementsById.get(responseKey);
    if (pictureElement?.type !== TSurveyElementTypeEnum.PictureSelection) {
      return;
    }

    normalizedResponses[responseKey] = pictureElement.choices
      .filter((choice) => selectedChoiceIds.includes(choice.id))
      .map((choice) => resolveStorageUrlAuto(choice.imageUrl));
  });

  // A Signature answer is one stored URL string (ADR 0023). Notion rejects a relative URL, so it goes out
  // absolute like every other integration's.
  mapping.forEach((map) => {
    const answer = normalizedResponses[map.element.id];
    if (
      surveyElementsById.get(map.element.id)?.type === TSurveyElementTypeEnum.Signature &&
      typeof answer === "string"
    ) {
      normalizedResponses[map.element.id] = resolveStorageUrlAuto(answer);
    }
  });

  mapping.forEach((map) => {
    if (map.element.id === "metadata") {
      properties[map.column.name] = {
        [map.column.type]: getValue(map.column.type, convertMetaObjectToString(data.response.meta)) || null,
      };
    } else if (map.element.id === "createdAt") {
      properties[map.column.name] = {
        [map.column.type]: getValue(map.column.type, data.response.createdAt) || null,
      };
    } else if (map.element.id.startsWith(NOTION_PERSON_ATTRIBUTE_PREFIX)) {
      const attributeKey = map.element.id.slice(NOTION_PERSON_ATTRIBUTE_PREFIX.length);
      const value = data.response.contactAttributes?.[attributeKey];
      properties[map.column.name] = {
        [map.column.type]: getValue(map.column.type, value) || null,
      };
    } else {
      const value = normalizedResponses[map.element.id];
      properties[map.column.name] = {
        [map.column.type]: getValue(map.column.type, value) || null,
      };
    }
  });

  return properties;
};

// notion requires specific payload for each column type
// * TYPES NOT SUPPORTED BY NOTION API - rollup, created_by, created_time, last_edited_by, or last_edited_time
type TNotionValueInput = string | string[] | Date | number | Record<string, string> | undefined;

const coerceToNotionString = (
  value: TNotionValueInput,
  options?: { allowArrays?: boolean }
): string | null => {
  if (value == null) {
    return null;
  }

  if (Array.isArray(value)) {
    if (!options?.allowArrays) {
      return null;
    }

    return value.join("\n");
  }

  if (value instanceof Date) {
    return value.toISOString();
  }

  if (typeof value === "object") {
    return JSON.stringify(value);
  }

  return String(value);
};

const getSelectValue = (value: TNotionValueInput) => {
  if (typeof value !== "string" || value.length === 0) {
    return null;
  }

  return {
    name: value.replaceAll(",", ""),
  };
};

const getMultiSelectValue = (value: TNotionValueInput) => {
  if (!Array.isArray(value)) {
    return null;
  }

  return (value as unknown[]).flatMap((entry) => {
    if (typeof entry === "string") {
      return [{ name: entry.replaceAll(",", "") }];
    }

    if (
      entry &&
      typeof entry === "object" &&
      "name" in entry &&
      typeof (entry as { name?: unknown }).name === "string"
    ) {
      return [{ name: (entry as { name: string }).name.replaceAll(",", "") }];
    }

    return [];
  });
};

const getTitleValue = (value: TNotionValueInput) => {
  const content = coerceToNotionString(value, { allowArrays: true });
  if (!content) {
    return null;
  }

  return [
    {
      text: {
        content,
      },
    },
  ];
};

const getRichTextValue = (value: TNotionValueInput) => {
  const content = coerceToNotionString(value, { allowArrays: true });
  if (!content) {
    return null;
  }

  return [
    {
      text: {
        content:
          content.length > NOTION_RICH_TEXT_LIMIT ? truncateText(content, NOTION_RICH_TEXT_LIMIT) : content,
      },
    },
  ];
};

const getUrlValue = (value: TNotionValueInput) => {
  if (Array.isArray(value)) {
    if (value.length !== 1) {
      return null;
    }

    return coerceToNotionString(value[0]);
  }

  const content = coerceToNotionString(value);
  if (!content) {
    return null;
  }

  if (typeof value === "string") {
    return value;
  }
  return content;
};

const getValue = (colType: string, value: TNotionValueInput) => {
  try {
    switch (colType) {
      case "select":
        return getSelectValue(value);
      case "multi_select":
        return getMultiSelectValue(value);
      case "title":
        return getTitleValue(value);
      case "rich_text":
        return getRichTextValue(value);
      case "status":
        return {
          name: value,
        };
      case "checkbox":
        return value === "accepted" || value === "clicked";
      case "date":
        return {
          start: value,
        };
      case "email":
        return value;
      case "number": {
        const numeric = typeof value === "number" ? value : Number(value);
        return Number.isFinite(numeric) ? numeric : null;
      }
      case "phone_number":
        return value;
      case "url":
        return getUrlValue(value);
      default:
        return null;
    }
  } catch (error) {
    logger.error(error, "Payload build failed!");
    throw new Error("Payload build failed!");
  }
};
