import { NextRequest, NextResponse } from 'next/server'
import { imChannelRepo } from '@/lib/database/repositories/im-channel.repo'
import { startLoginQr, pollLoginQrStatus } from '@/lib/im/adapters/weixin/weixin-api'
import { normalizeQrCodeUrl } from '@/lib/qrcode'

function normalizeQrLoginStatus(status?: string | null): 'pending' | 'scanned' | 'confirmed' | 'expired' {
    if (status === 'confirmed' || status === 'expired') return status
    if (status === 'scaned' || status === 'scanned') return 'scanned'
    return 'pending'
}

export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
    const { id } = await params

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

    const action = body.action
    if (action !== 'start' && action !== 'poll') {
        return NextResponse.json({ error: 'action must be "start" or "poll"' }, { status: 400 })
    }

    // Validate channel exists and is weixin
    const channel = imChannelRepo.findById(id)
    if (!channel) return NextResponse.json({ error: 'Channel not found' }, { status: 404 })
    if (channel.type !== 'weixin') {
        return NextResponse.json({ error: 'Channel is not a WeChat channel' }, { status: 400 })
    }

    try {
        if (action === 'start') {
            const resp = await startLoginQr()
            if (resp.errcode && resp.errcode !== 0) {
                return NextResponse.json({ error: resp.errmsg || 'Failed to start QR login' }, { status: 500 })
            }
            if (!resp.qrcode) {
                return NextResponse.json({ error: 'No qrcode returned' }, { status: 500 })
            }
            return NextResponse.json({
                status: 'pending',
                qrcode_key: resp.qrcode,
                qrcode_url: normalizeQrCodeUrl(resp.qrcode_img_content),
            })
        } else {
            // action === 'poll'
            const qrcode = body.qrcode_key
            if (!qrcode) {
                return NextResponse.json({ error: 'qrcode_key is required for poll' }, { status: 400 })
            }

            const resp = await pollLoginQrStatus(qrcode)
            if (resp.errcode && resp.errcode !== 0) {
                return NextResponse.json({ error: resp.errmsg || 'Failed to poll QR status' }, { status: 500 })
            }

            const status = normalizeQrLoginStatus(resp.status)
            if (status === 'confirmed') {
                const token = resp.bot_token
                const ilinkBotId = resp.ilink_bot_id
                const baseurl = resp.baseurl
                const ilinkUserId = resp.ilink_user_id

                if (!token) {
                    return NextResponse.json({ error: 'Login confirmed but no token received' }, { status: 500 })
                }

                return NextResponse.json({
                    status: 'confirmed',
                    token,
                    ilink_bot_id: ilinkBotId,
                    baseurl,
                    ilink_user_id: ilinkUserId,
                })
            }

            return NextResponse.json({ status })
        }
    } catch (err) {
        const errorMsg = err instanceof Error ? err.message : 'Unknown error'
        return NextResponse.json({ error: errorMsg }, { status: 500 })
    }
}
