/**
 * Telegram bot integration schema — telegram-bot (wave-8 leaf9).
 * Postgres / Neon via Hyperdrive.
 *
 * Tables:
 *  - telegram_chats: per-tenant linked Telegram chats / channels
 */
import { pgTable, uuid, text, boolean, timestamp } from 'drizzle-orm/pg-core'
import { sql } from 'drizzle-orm'
import { check, unique } from 'drizzle-orm/pg-core'
import { tenants } from './tenants'

// ── telegram_chats ────────────────────────────────────────────────────────────

export const telegramChats = pgTable(
  'telegram_chats',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    tenantId: uuid('tenant_id')
      .notNull()
      .references(() => tenants.id, { onDelete: 'cascade' }),
    // Telegram chat_id (numeric as text — can be negative for groups)
    chatId: text('chat_id').notNull(),
    // private|group|supergroup|channel
    chatType: text('chat_type').notNull(),
    chatTitle: text('chat_title'),
    // Zync user who linked this chat
    linkedUserId: uuid('linked_user_id'),
    isActive: boolean('is_active').default(true),
    createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
  },
  (t) => ({
    chatTypeCheck: check(
      'telegram_chats_chat_type_check',
      sql`${t.chatType} IN ('private','group','supergroup','channel')`,
    ),
    // One row per (tenant, chat) — a chat may be linked to multiple tenants but
    // in practice each chat should only belong to one tenant.
    tenantChatUniq: unique('telegram_chats_tenant_chat_uniq').on(t.tenantId, t.chatId),
  }),
)

export type TelegramChatRow = typeof telegramChats.$inferSelect
export type NewTelegramChat = typeof telegramChats.$inferInsert
