import { NextRequest, NextResponse } from 'next/server'
import { ConfigManager } from '@/remote-control/config/manager'

function sleep(ms: number) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

/**
 * Poll a bot's getStatus() until it leaves 'connecting' state,
 * or until timeout (default 10s). Returns the final status.
 */
async function waitForConnection(
  getStatus: () => { status: string; error?: string },
  timeoutMs = 10000,
  intervalMs = 500,
): Promise<{ status: string; error?: string }> {
  const deadline = Date.now() + timeoutMs
  while (Date.now() < deadline) {
    const s = getStatus()
    // 'connected' or 'disconnected' (with error) means we have a definitive answer
    if (s.status !== 'connecting') return s
    await sleep(intervalMs)
  }
  return getStatus()
}

export async function POST(request: NextRequest) {
  try {
    const { platform } = await request.json()

    if (platform !== 'discord' && platform !== 'dingtalk' && platform !== 'lark' && platform !== 'telegram' && platform !== 'slack') {
      return NextResponse.json({ success: false, error: '无效的平台' }, { status: 400 })
    }

    const mgr = ConfigManager.getInstance()
    await mgr.ensureLoaded()
    const config = mgr.get()

    // Reject test for disabled platforms
    const platformConfig = config[platform as keyof typeof config] as { enabled: boolean }
    if (!platformConfig?.enabled) {
      return NextResponse.json({ success: false, error: '该渠道已禁用，请先启用后再测试' }, { status: 400 })
    }

    if (platform === 'discord') {
      if (!config.discord.botToken) {
        return NextResponse.json({ success: false, error: 'Discord Bot Token 未配置' })
      }
      try {
        const bot = await import('@/remote-control/bots/discord')
        await bot.stopBot()
        await bot.startBot(config.discord.botToken)
        const status = await waitForConnection(() => bot.getStatus())
        return NextResponse.json({
          success: status.status === 'connected',
          status,
          error: status.status !== 'connected' ? (status.error || '连接超时，请检查 Token 是否正确') : undefined,
        })
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err)
        return NextResponse.json({ success: false, error: `Discord 连接失败: ${msg}` })
      }
    }

    if (platform === 'dingtalk') {
      if (!config.dingtalk.clientId || !config.dingtalk.clientSecret) {
        return NextResponse.json({ success: false, error: '钉钉 Client ID 或 Client Secret 未配置' })
      }
      try {
        const bot = await import('@/remote-control/bots/dingtalk')
        await bot.stopBot()
        await bot.startBot(config.dingtalk.clientId, config.dingtalk.clientSecret)
        const status = await waitForConnection(() => bot.getStatus())
        return NextResponse.json({
          success: status.status === 'connected',
          status,
          error: status.status !== 'connected' ? (status.error || '连接超时，请检查凭证是否正确') : undefined,
        })
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err)
        return NextResponse.json({ success: false, error: `钉钉连接失败: ${msg}` })
      }
    }

    if (platform === 'lark') {
      if (!config.lark.appId || !config.lark.appSecret) {
        return NextResponse.json({ success: false, error: '飞书 App ID 或 App Secret 未配置' })
      }
      try {
        const bot = await import('@/remote-control/bots/lark')
        await bot.stopBot()
        await bot.startBot(config.lark.appId, config.lark.appSecret)
        const status = await waitForConnection(() => bot.getStatus())
        return NextResponse.json({
          success: status.status === 'connected',
          status,
          error: status.status !== 'connected' ? (status.error || '连接超时，请检查凭证是否正确') : undefined,
        })
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err)
        return NextResponse.json({ success: false, error: `飞书连接失败: ${msg}` })
      }
    }

    if (platform === 'telegram') {
      if (!config.telegram.botToken) {
        return NextResponse.json({ success: false, error: 'Telegram Bot Token 未配置' })
      }
      try {
        const bot = await import('@/remote-control/bots/telegram')
        await bot.stopBot()
        await bot.startBot(config.telegram.botToken)
        const status = await waitForConnection(() => bot.getStatus())
        return NextResponse.json({
          success: status.status === 'connected',
          status,
          error: status.status !== 'connected' ? (status.error || '连接超时，请检查 Token 是否正确') : undefined,
        })
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err)
        return NextResponse.json({ success: false, error: `Telegram 连接失败: ${msg}` })
      }
    }

    if (platform === 'slack') {
      if (!config.slack.botToken || !config.slack.appToken) {
        return NextResponse.json({ success: false, error: 'Slack Bot Token 或 App Token 未配置' })
      }
      try {
        const bot = await import('@/remote-control/bots/slack')
        await bot.stopBot()
        await bot.startBot(config.slack.botToken, config.slack.appToken)
        const status = await waitForConnection(() => bot.getStatus())
        return NextResponse.json({
          success: status.status === 'connected',
          status,
          error: status.status !== 'connected' ? (status.error || '连接超时，请检查凭证是否正确') : undefined,
        })
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err)
        return NextResponse.json({ success: false, error: `Slack 连接失败: ${msg}` })
      }
    }
  } catch {
    return NextResponse.json({ success: false, error: '请求解析失败' }, { status: 400 })
  }
}
