import {NextRequest, NextResponse} from 'next/server'
import {createChannels} from '@/actions/channel'

export async function GET(req: NextRequest) {
  try {
    const params = req.nextUrl.searchParams

    const resource_id = params.get('i')
    if (!resource_id) {
      throw new Error('需要指定资源ID')
    }
    let protocol = params.get('x')
    if (!protocol) {
      protocol = '1'
    }
    const auth_type = params.get('t')
    if (!auth_type) {
      throw new Error('需要指定认证类型')
    }
    const count = params.get('n')
    if (!count) {
      throw new Error('需要指定通道创建数量')
    }
    const prov = params.get('a') || undefined
    const city = params.get('b') || undefined
    const isp = params.get('s') || undefined

    const result = await createChannels({
      resource_id: Number(resource_id),
      auth_type: Number(auth_type),
      protocol: Number(protocol),
      count: Number(count),
      prov,
      city,
      isp: Number(isp),
    })
    if (!result.success) {
      throw new Error(result.message)
    }

    const format = params.get('rt')
    const rBreaker = params.get('rb') || '13,10'
    const rSeparator = params.get('rs') || '124'

    const breaker = rBreaker.split(',').map(code => String.fromCharCode(parseInt(code))).join('')
    const separator = rSeparator.split(',').map(code => String.fromCharCode(parseInt(code))).join('')

    switch (format) {
    case 'json':
      return NextResponse.json(result.data)
    case 'text':
      const text = result.data.map((item) => {
        const list = [item.host, item.port]
        if (item.username && item.password) {
          list.push(item.username)
          list.push(item.password)
        }
        return list.join(separator)
      }).join(breaker)
      return new NextResponse(text)
    }
  }
  catch (error) {
    console.error('Error creating channels:', error)
    return NextResponse.json({error: (error as Error).message})
  }
}
