import { sqliteTable, text, index } from 'drizzle-orm/sqlite-core'
import { sql } from 'drizzle-orm'

export const channelOutboundRefs = sqliteTable(
  'channel_outbound_refs',
  {
    id: text('id').primaryKey(),
    channelType: text('channel_type').notNull(),
    chatId: text('chat_id').notNull(),
    internalId: text('internal_id').notNull(),
    platformMsgId: text('platform_msg_id').notNull(),
    createdAt: text('created_at').notNull().default(sql`(datetime('now'))`),
  },
  (t) => ({
    lookupIdx: index('idx_outbound_refs_lookup').on(t.channelType, t.chatId, t.internalId),
  }),
)

export type ChannelOutboundRef = typeof channelOutboundRefs.$inferSelect

export const channelAuditLogs = sqliteTable(
  'channel_audit_logs',
  {
    id: text('id').primaryKey(),
    channelType: text('channel_type').notNull(),
    chatId: text('chat_id').notNull(),
    action: text('action').notNull(),
    details: text('details').notNull().default('{}'),
    createdAt: text('created_at').notNull().default(sql`(datetime('now'))`),
  },
  (t) => ({
    timeIdx: index('idx_audit_logs_time').on(t.createdAt),
  }),
)

export type ChannelAuditLog = typeof channelAuditLogs.$inferSelect

export const channelDedupe = sqliteTable('channel_dedupe', {
  hash: text('hash').primaryKey(),
  channelType: text('channel_type').notNull(),
  chatId: text('chat_id').notNull(),
  createdAt: text('created_at').notNull().default(sql`(datetime('now'))`),
})

export type ChannelDedupe = typeof channelDedupe.$inferSelect
