import { z } from "zod";
import { TSurveyElementTypeEnum } from "./surveys/constants";

// Feedback source type enum
export const ZFeedbackSourceType = z.enum(["formbricks_survey", "csv"]);
export type TFeedbackSourceType = z.infer<typeof ZFeedbackSourceType>;

// Feedback source status enum
export const ZFeedbackSourceStatus = z.enum(["active", "paused", "error"]);
export type TFeedbackSourceStatus = z.infer<typeof ZFeedbackSourceStatus>;

/**
 * Which survey responses a Formbricks feedback source imports into Hub.
 *
 * `completedOnly` matches the live ingestion path, which only runs on `responseFinished`.
 * `all` additionally imports partial responses — answers a respondent typed but never submitted —
 * which also means that text reaches Hub's LLM enrichments. Keep `completedOnly` the default.
 */
export const ZFeedbackSourceImportMode = z.enum(["completedOnly", "all"]);
export type TFeedbackSourceImportMode = z.infer<typeof ZFeedbackSourceImportMode>;

/**
 * Whether a formbricks_survey source tracks every supported element of the surveys it maps, or an
 * explicit subset. Always derived server-side from the submitted selection — never accepted from a
 * client — so the scope can never disagree with the mapping rows it describes.
 *
 * Orthogonal to `importMode`: that one decides WHICH responses are imported, this one decides WHICH
 * QUESTIONS a response is imported for.
 */
export const ZFeedbackSourceElementScope = z.enum(["all", "specific"]);
export type TFeedbackSourceElementScope = z.infer<typeof ZFeedbackSourceElementScope>;

// Hub field types (from Hub OpenAPI spec)
export const ZHubFieldType = z.enum([
  "text",
  "categorical",
  "nps",
  "csat",
  "ces",
  "rating",
  "number",
  "boolean",
  "date",
]);
export type THubFieldType = z.infer<typeof ZHubFieldType>;

// Hub enrichment vocabularies (from Hub OpenAPI spec), in the Hub's own order: sentiment runs from most
// negative to most positive, with "mixed" last. The single source for the v3 feedback-record filter
// schemas below and for every label map in the app, which is typed `Record<THubSentiment | THubEmotion, …>`
// so that adding a label fails the build until every map is updated. The Hub caps its `sentiment` and
// `emotions` filters at these cardinalities rather than at the generic 100-value limit, since more
// entries than there are labels can only be duplicates.
export const HUB_SENTIMENT_VALUES = [
  "very_negative",
  "negative",
  "neutral",
  "positive",
  "very_positive",
  "mixed",
] as const;

export const HUB_EMOTION_VALUES = ["joy", "anger", "sadness", "fear", "surprise", "disgust"] as const;

export const ZHubSentiment = z.enum(HUB_SENTIMENT_VALUES);
export type THubSentiment = z.infer<typeof ZHubSentiment>;

export const ZHubEmotion = z.enum(HUB_EMOTION_VALUES);
export type THubEmotion = z.infer<typeof ZHubEmotion>;

// Hub target fields for mapping.
// `response_value` is a CSV-only synthetic id stored in FeedbackSourceFieldMapping; csv-transform.ts
// resolves it to the appropriate value_* target before any Hub write — the Hub never sees it.
export const ZHubTargetField = z.enum([
  "collected_at",
  "source_type",
  "field_id",
  "field_type",
  "field_label",
  "field_group_id",
  "field_group_label",
  "tenant_id",
  "source_id",
  "source_name",
  "value_text",
  "value_number",
  "value_boolean",
  "value_date",
  "metadata",
  "language",
  "user_id",
  "submission_id",
  "response_value",
]);
export type THubTargetField = z.infer<typeof ZHubTargetField>;

// Base feedback source schema
export const ZFeedbackSource = z.object({
  id: z.cuid2(),
  createdAt: z.date(),
  updatedAt: z.date(),
  name: z.string().min(1),
  type: ZFeedbackSourceType,
  status: ZFeedbackSourceStatus,
  importMode: ZFeedbackSourceImportMode,
  elementScope: ZFeedbackSourceElementScope,
  workspaceId: z.cuid2(),
  feedbackDirectoryId: z.cuid2(),
  lastSyncAt: z.date().nullable(),
  createdBy: z.string().nullable(),
});
export type TFeedbackSource = z.infer<typeof ZFeedbackSource>;

// Formbricks element mapping
export const ZFeedbackSourceFormbricksMapping = z.object({
  id: z.cuid2(),
  createdAt: z.date(),
  feedbackSourceId: z.cuid2(),
  workspaceId: z.cuid2(),
  surveyId: z.cuid2(),
  elementId: z.string(),
  hubFieldType: ZHubFieldType,
  customFieldLabel: z.string().nullable(),
});
export type TFeedbackSourceFormbricksMapping = z.infer<typeof ZFeedbackSourceFormbricksMapping>;

export const ZFeedbackSourceFieldMapping = z.object({
  id: z.cuid2(),
  createdAt: z.date(),
  feedbackSourceId: z.cuid2(),
  workspaceId: z.cuid2(),
  sourceFieldId: z.string(),
  targetFieldId: ZHubTargetField,
  staticValue: z.string().nullable(),
});
export type TFeedbackSourceFieldMapping = z.infer<typeof ZFeedbackSourceFieldMapping>;

export const ZFeedbackSourceWithMappings = ZFeedbackSource.extend({
  formbricksMappings: z.array(ZFeedbackSourceFormbricksMapping),
  fieldMappings: z.array(ZFeedbackSourceFieldMapping),
  creatorName: z.string().nullable().optional(),
});
export type TFeedbackSourceWithMappings = z.infer<typeof ZFeedbackSourceWithMappings>;

// Create input schemas
export const ZFeedbackSourceCreateInput = z.object({
  name: z.string().min(1),
  type: ZFeedbackSourceType,
  feedbackDirectoryId: z.cuid2(),
  // Optional so callers that do not care inherit the schema default (completedOnly).
  importMode: ZFeedbackSourceImportMode.optional(),
  createdBy: z.cuid2().optional(),
});
export type TFeedbackSourceCreateInput = z.infer<typeof ZFeedbackSourceCreateInput>;

// Create Formbricks mapping input
export const ZFeedbackSourceFormbricksMappingCreateInput = z.object({
  surveyId: z.cuid2(),
  elementId: z.string(),
  hubFieldType: ZHubFieldType,
  customFieldLabel: z.string().optional(),
});
export type TFeedbackSourceFormbricksMappingCreateInput = z.infer<
  typeof ZFeedbackSourceFormbricksMappingCreateInput
>;

// Create field mapping input
export const ZFeedbackSourceFieldMappingCreateInput = z.object({
  sourceFieldId: z.string(),
  targetFieldId: ZHubTargetField,
  staticValue: z.string().optional(),
});
export type TFeedbackSourceFieldMappingCreateInput = z.infer<typeof ZFeedbackSourceFieldMappingCreateInput>;

// Update feedback source input
export const ZFeedbackSourceUpdateInput = z.object({
  name: z.string().min(1).optional(),
  status: ZFeedbackSourceStatus.optional(),
  importMode: ZFeedbackSourceImportMode.optional(),
  lastSyncAt: z.date().nullable().optional(),
});
export type TFeedbackSourceUpdateInput = z.infer<typeof ZFeedbackSourceUpdateInput>;

// Element types that cannot be mapped to Hub fields
export const UNSUPPORTED_FEEDBACK_SOURCE_ELEMENT_TYPES: readonly TSurveyElementTypeEnum[] = [
  TSurveyElementTypeEnum.ContactInfo,
  TSurveyElementTypeEnum.Address,
  TSurveyElementTypeEnum.Cal,
  TSurveyElementTypeEnum.CTA,
  TSurveyElementTypeEnum.FileUpload,
  TSurveyElementTypeEnum.Signature,
  TSurveyElementTypeEnum.Consent,
] as const;

// Element type to Hub field type mapping helper (only supported types)
export const ELEMENT_TYPE_TO_HUB_FIELD_TYPE: Record<string, THubFieldType> = {
  openText: "text",
  nps: "nps",
  csat: "csat",
  ces: "ces",
  rating: "rating",
  multipleChoiceSingle: "categorical",
  multipleChoiceMulti: "categorical",
  date: "date",
  matrix: "categorical",
  ranking: "categorical",
  pictureSelection: "categorical",
};

// Helper function to get Hub field type from element type
export const getHubFieldTypeFromElementType = (elementType: string): THubFieldType | undefined => {
  return ELEMENT_TYPE_TO_HUB_FIELD_TYPE[elementType];
};
