import { sqliteTable, text, uniqueIndex, index } from 'drizzle-orm/sqlite-core'
import { sql } from 'drizzle-orm'
import { PairingStatus } from '../../shared/enums'

export const weixinContextTokens = sqliteTable(
  'weixin_context_tokens',
  {
    id: text('id').primaryKey(),
    channelId: text('channel_id').notNull(),
    peerUserId: text('peer_user_id').notNull(),
    contextToken: text('context_token').notNull(),
    updatedAt: text('updated_at').notNull().default(sql`(datetime('now'))`),
  },
  (t) => ({
    channelPeerUnique: uniqueIndex('weixin_context_tokens_channel_id_peer_user_id_unique').on(
      t.channelId,
      t.peerUserId,
    ),
    lookupIdx: index('idx_weixin_ctx_token').on(t.channelId, t.peerUserId),
  }),
)

export type WeixinContextToken = typeof weixinContextTokens.$inferSelect

export const weixinSyncCursors = sqliteTable('weixin_sync_cursors', {
  channelId: text('channel_id').primaryKey(),
  getUpdatesBuf: text('get_updates_buf').notNull(),
  updatedAt: text('updated_at').notNull().default(sql`(datetime('now'))`),
})

export type WeixinSyncCursor = typeof weixinSyncCursors.$inferSelect

export const imPairingRequests = sqliteTable(
  'im_pairing_requests',
  {
    id: text('id').primaryKey(),
    channelId: text('channel_id').notNull(),
    senderId: text('sender_id').notNull(),
    code: text('code').notNull(),
    status: text('status', { enum: ['pending', 'approved', 'expired'] })
      .notNull()
      .default(PairingStatus.PENDING),
    createdAt: text('created_at').notNull().default(sql`(datetime('now'))`),
    expiresAt: text('expires_at').notNull().default(sql`(datetime('now', '+10 minutes'))`),
    verifiedAt: text('verified_at'),
  },
  (t) => ({
    channelSenderIdx: index('idx_pairing_channel_sender').on(t.channelId, t.senderId, t.status),
  }),
)

export type ImPairingRequest = typeof imPairingRequests.$inferSelect
