import { NextResponse } from "next/server"

const WAHA_URL = process.env.WAHA_API_URL || "https://waha.quikcue.com"
const WAHA_KEY = process.env.WAHA_API_KEY || "qc-waha-api-7Fp3nR9xYm2K"
const WAHA_SESSION = process.env.WAHA_SESSION || "default"

async function wahaGet(path: string) {
  const res = await fetch(`${WAHA_URL}${path}`, {
    headers: { "X-Api-Key": WAHA_KEY },
    signal: AbortSignal.timeout(8000),
    cache: "no-store",
  })
  return res
}

/**
 * GET /api/whatsapp/qr
 * Returns session status. For QR scanning, provides the screenshot
 * cropped to the QR code area, or a link to the WAHA dashboard.
 */
export async function GET() {
  try {
    const sessRes = await wahaGet("/api/sessions")
    const sessions = await sessRes.json()
    const session = Array.isArray(sessions)
      ? sessions.find((s: { name: string }) => s.name === WAHA_SESSION)
      : null

    if (!session) {
      return NextResponse.json({ status: "NO_SESSION" })
    }

    if (session.status === "WORKING") {
      return NextResponse.json({
        status: "CONNECTED",
        phone: session.me?.id?.replace("@c.us", "") || "",
        pushName: session.me?.pushname || "",
      })
    }

    if (session.status === "SCAN_QR_CODE") {
      // Get screenshot from WAHA and return as base64
      try {
        const ssRes = await wahaGet(`/api/screenshot?session=${WAHA_SESSION}`)
        if (ssRes.ok) {
          const buf = await ssRes.arrayBuffer()
          const b64 = Buffer.from(buf).toString("base64")
          return NextResponse.json({
            status: "SCAN_QR_CODE",
            screenshot: `data:image/png;base64,${b64}`,
            message: "Scan the QR code with WhatsApp → Linked Devices → Link a Device",
          })
        }
      } catch { /* fall through */ }

      return NextResponse.json({
        status: "SCAN_QR_CODE",
        screenshot: null,
        message: "QR loading... Refresh in a moment.",
      })
    }

    return NextResponse.json({ status: session.status })
  } catch (error) {
    console.error("WhatsApp QR error:", error)
    return NextResponse.json({ status: "ERROR", error: String(error) })
  }
}

/**
 * POST /api/whatsapp/qr - Start or restart session
 */
export async function POST() {
  try {
    const sessRes = await wahaGet("/api/sessions")
    const sessions = await sessRes.json()
    const existing = Array.isArray(sessions)
      ? sessions.find((s: { name: string }) => s.name === WAHA_SESSION)
      : null

    if (existing) {
      await fetch(`${WAHA_URL}/api/sessions/stop`, {
        method: "POST",
        headers: { "Content-Type": "application/json", "X-Api-Key": WAHA_KEY },
        body: JSON.stringify({ name: WAHA_SESSION }),
        signal: AbortSignal.timeout(10000),
      }).catch(() => {})
      await new Promise(r => setTimeout(r, 2000))
    }

    const startRes = await fetch(`${WAHA_URL}/api/sessions/start`, {
      method: "POST",
      headers: { "Content-Type": "application/json", "X-Api-Key": WAHA_KEY },
      body: JSON.stringify({
        name: WAHA_SESSION,
        config: {
          webhooks: [{
            url: `${process.env.BASE_URL || "https://pledge.quikcue.com"}/api/whatsapp/webhook`,
            events: ["message", "session.status"],
          }],
        },
      }),
      signal: AbortSignal.timeout(15000),
    })
    const result = await startRes.json()
    return NextResponse.json({ success: true, status: result.status || "STARTING" })
  } catch (error) {
    return NextResponse.json({ success: false, error: String(error) })
  }
}
