/**
 * Feishu card config reader — 从 bridge-manager 迁入（C-2.1）。
 * 读取 im_channels.credentials 中的飞书卡片配置（replyMode/footer），
 * 供 FeishuStreamRenderer 与 bridge.deliverPlatformFinal 复用。
 */

import { imChannelRepo } from '@/lib/database/repositories/im-channel.repo'
import type { FeishuCardConfig } from '../../types'

/** Read Feishu card config from channel credentials JSON. */
export function getFeishuCardConfig(channelId: string): FeishuCardConfig {
  const defaultConfig: FeishuCardConfig = { replyMode: 'auto', footer: { status: true, elapsed: true, model: true } }
  // findCredentials 取单列 credentials（与原 `SELECT credentials FROM im_channels WHERE id=?` 等价）；
  // 字段为 drizzle 推断的 camelCase。
  const channel = imChannelRepo.findCredentials(channelId)
  if (!channel) return defaultConfig
  try {
    const creds = JSON.parse(channel.credentials) as Record<string, unknown>
    // Card config can be a JSON string (from frontend) or a nested object (from API)
    let cardConfig: Record<string, unknown> | undefined
    if (typeof creds.card === 'string') {
      cardConfig = JSON.parse(creds.card) as Record<string, unknown>
    } else if (typeof creds.card === 'object' && creds.card !== null) {
      cardConfig = creds.card as Record<string, unknown>
    }
    // Legacy `streaming: boolean` (removed) mapped to replyMode for backward compat:
    //   streaming:true  -> 'auto' (streaming-on when available)
    //   streaming:false -> 'static' (user explicitly disabled streaming)
    // An explicit replyMode always wins over the legacy boolean.
    const legacyStreaming = typeof cardConfig?.streaming === 'boolean' ? cardConfig.streaming : null
    const explicitReplyMode = cardConfig?.replyMode as FeishuCardConfig['replyMode'] | undefined
    const replyMode: FeishuCardConfig['replyMode'] = explicitReplyMode
      ?? (legacyStreaming === false ? 'static' : 'auto')
    const footerObj = cardConfig?.footer as Record<string, unknown> | undefined
    return {
      replyMode: replyMode === 'static' || replyMode === 'streaming' ? replyMode : 'auto',
      footer: {
        status: (footerObj?.status as boolean) ?? true,
        elapsed: (footerObj?.elapsed as boolean) ?? true,
        model: (footerObj?.model as boolean) ?? true,
      },
    }
  } catch {
    return defaultConfig
  }
}
