import { NextRequest, NextResponse } from 'next/server'
import { imChannelRepo } from '@/lib/database/repositories/im-channel.repo'
import { getBridgeManager } from '@/lib/im/core/bridge-manager'
import crypto from 'crypto'
import { isAuthError, requireUser } from '@/lib/auth/session'

export async function GET(req: NextRequest) {
  try {
    const user = await requireUser()
    // Ensure BridgeManager is initialized (triggers auto-reconnect on first call)
    getBridgeManager()

    const { searchParams } = new URL(req.url)
    const workspaceId = searchParams.get('workspace_id')

    const rows = workspaceId
      ? imChannelRepo.listConnectedByOwnerAndWorkspace(user.id, workspaceId)
      : imChannelRepo.listByOwner(user.id)
    return NextResponse.json(rows)
  } catch (err) {
    if (isAuthError(err)) return err
    throw err
  }
}

export async function POST(req: NextRequest) {
  let user
  try {
    user = await requireUser()
  } catch (err) {
    if (isAuthError(err)) return err
    throw err
  }

  let body: { type?: string; name?: string }
  try {
    body = await req.json()
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
  }

  const type = body.type
  if (
    type !== 'telegram'
    && type !== 'feishu'
    && type !== 'discord'
    && type !== 'weixin'
    && type !== 'dingtalk'
    && type !== 'wecom'
  ) {
    return NextResponse.json({ error: 'type must be telegram, feishu, discord, weixin, dingtalk, or wecom' }, { status: 400 })
  }

  const count = imChannelRepo.countByTypeAndOwner(type, user.id)
  const defaultName = `${type[0].toUpperCase()}${type.slice(1)} Bot ${count + 1}`

  const id = crypto.randomUUID()
  const row = imChannelRepo.create({
    id,
    type,
    name: body.name?.trim() || defaultName,
    ownerUserId: user.id,
  })
  return NextResponse.json(row, { status: 201 })
}
