import { createId } from "@paralleldrive/cuid2";

export const CONTENT_TOPICS = {
  TEXTBOOK: "edu.content.textbook.events",
  CHAPTER: "edu.content.chapter.events",
  KNOWLEDGE_POINT: "edu.content.knowledge_point.events",
  QUESTION: "edu.content.question.events",
} as const;

export const AGGREGATE_TYPES = {
  TEXTBOOK: "Textbook",
  CHAPTER: "Chapter",
  KNOWLEDGE_POINT: "KnowledgePoint",
  QUESTION: "Question",
} as const;

export const EVENT_TYPES = {
  TEXTBOOK_CREATED: "textbook.created",
  TEXTBOOK_UPDATED: "textbook.updated",
  TEXTBOOK_PUBLISHED: "textbook.published",
  TEXTBOOK_ARCHIVED: "textbook.archived",
  CHAPTER_CREATED: "chapter.created",
  CHAPTER_UPDATED: "chapter.updated",
  CHAPTER_DELETED: "chapter.deleted",
  KP_CREATED: "knowledge_point.created",
  KP_UPDATED: "knowledge_point.updated",
  KP_PREREQUISITE_ADDED: "knowledge_point.prerequisite_added",
  KP_PREREQUISITE_REMOVED: "knowledge_point.prerequisite_removed",
  QUESTION_CREATED: "question.created",
  QUESTION_UPDATED: "question.updated",
  QUESTION_PUBLISHED: "question.published",
  QUESTION_DELETED: "question.deleted",
} as const;

const TOPIC_MAP: Record<string, string> = {
  [EVENT_TYPES.TEXTBOOK_CREATED]: CONTENT_TOPICS.TEXTBOOK,
  [EVENT_TYPES.TEXTBOOK_UPDATED]: CONTENT_TOPICS.TEXTBOOK,
  [EVENT_TYPES.TEXTBOOK_PUBLISHED]: CONTENT_TOPICS.TEXTBOOK,
  [EVENT_TYPES.TEXTBOOK_ARCHIVED]: CONTENT_TOPICS.TEXTBOOK,
  [EVENT_TYPES.CHAPTER_CREATED]: CONTENT_TOPICS.CHAPTER,
  [EVENT_TYPES.CHAPTER_UPDATED]: CONTENT_TOPICS.CHAPTER,
  [EVENT_TYPES.CHAPTER_DELETED]: CONTENT_TOPICS.CHAPTER,
  [EVENT_TYPES.KP_CREATED]: CONTENT_TOPICS.KNOWLEDGE_POINT,
  [EVENT_TYPES.KP_UPDATED]: CONTENT_TOPICS.KNOWLEDGE_POINT,
  [EVENT_TYPES.KP_PREREQUISITE_ADDED]: CONTENT_TOPICS.KNOWLEDGE_POINT,
  [EVENT_TYPES.KP_PREREQUISITE_REMOVED]: CONTENT_TOPICS.KNOWLEDGE_POINT,
  [EVENT_TYPES.QUESTION_CREATED]: CONTENT_TOPICS.QUESTION,
  [EVENT_TYPES.QUESTION_UPDATED]: CONTENT_TOPICS.QUESTION,
  [EVENT_TYPES.QUESTION_PUBLISHED]: CONTENT_TOPICS.QUESTION,
  [EVENT_TYPES.QUESTION_DELETED]: CONTENT_TOPICS.QUESTION,
};

export function getTopicForEvent(eventType: string): string {
  return TOPIC_MAP[eventType] ?? "edu.content.fallback";
}

export interface EventPayload {
  event_id: string;
  aggregate_id: string;
  event_type: string;
  occurred_at: number;
  action: string;
  [key: string]: unknown;
}

export function buildEventPayload(
  eventType: string,
  aggregateId: string,
  data: Record<string, unknown>,
): EventPayload {
  const action = eventType.split(".").pop() ?? eventType;
  return {
    event_id: createId(),
    aggregate_id: aggregateId,
    event_type: `edu.content.${eventType}`,
    occurred_at: Date.now(),
    action,
    ...data,
  };
}
