import {
  mysqlTable,
  varchar,
  text,
  timestamp,
  int,
  index,
} from "drizzle-orm/mysql-core";

export const outbox = mysqlTable(
  "content_outbox_events",
  {
    id: varchar("id", { length: 32 }).notNull().primaryKey(),
    aggregateType: varchar("aggregate_type", { length: 64 }).notNull(),
    aggregateId: varchar("aggregate_id", { length: 32 }).notNull(),
    eventType: varchar("event_type", { length: 100 }).notNull(),
    topic: varchar("topic", { length: 128 }).notNull(),
    payload: text("payload").notNull(),
    status: varchar("status", { length: 20 }).notNull().default("pending"),
    retryCount: int("retry_count").notNull().default(0),
    createdAt: timestamp("created_at").notNull().defaultNow(),
    publishedAt: timestamp("published_at"),
    nextRetryAt: timestamp("next_retry_at"),
    lastError: text("last_error"),
  },
  (table) => ({
    statusRetryIdx: index("idx_outbox_status_retry").on(
      table.status,
      table.nextRetryAt,
    ),
    aggregateIdx: index("idx_outbox_aggregate").on(
      table.aggregateType,
      table.aggregateId,
    ),
  }),
);

export type OutboxMessage = typeof outbox.$inferSelect;
export type NewOutboxMessage = typeof outbox.$inferInsert;
