import { NextRequest, NextResponse } from "next/server"

import { createMachineSession, MachineInactiveError } from "@/server/machines-session"
import { env } from "@/lib/env"

const INACTIVE_TEMPLATE = `
<!doctype html>
<html lang="pt-BR">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Dispositivo desativada</title>
    <style>
      :root { color-scheme: dark light; }
      body { font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background-color: #0f172a; color: #e2e8f0; margin: 0; display: grid; place-items: center; min-height: 100vh; padding: 24px; }
      main { width: min(480px, 100%); padding: 32px; border-radius: 16px; background: linear-gradient(145deg, rgba(15,23,42,0.85), rgba(15,23,42,0.65)); box-shadow: 0 18px 42px rgba(15, 23, 42, 0.45); text-align: center; backdrop-filter: blur(14px); border: 1px solid rgba(226, 232, 240, 0.08); }
      h1 { margin: 0 0 12px; font-size: 1.7rem; letter-spacing: -0.01em; }
      p { margin: 8px 0; line-height: 1.6; color: rgba(226,232,240,0.88); }
      a { display: inline-flex; align-items: center; justify-content: center; gap: 8px; margin-top: 22px; padding: 12px 18px; border-radius: 999px; background-color: #00d6eb; color: #0f172a; text-decoration: none; font-weight: 600; transition: background-color 0.2s ease, transform 0.2s ease; }
      a:hover { background-color: #1af0ff; transform: translateY(-1px); }
      .badge { display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; border-radius: 999px; background: rgba(248, 113, 113, 0.12); color: #fecaca; font-size: 0.75rem; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; margin-bottom: 12px; }
    </style>
  </head>
  <body>
    <main>
      <div class="badge">Acesso bloqueado</div>
      <h1>Esta dispositivo está desativada</h1>
      <p>O acesso ao portal foi suspenso pelos administradores da Rever. Enquanto isso, você não poderá abrir chamados ou enviar atualizações.</p>
      <p>Entre em contato com a equipe da Rever para solicitar a reativação desta dispositivo.</p>
      <a href="mailto:suporte@rever.com.br">Falar com o suporte</a>
    </main>
  </body>
</html>
`

export async function GET(request: NextRequest) {
  const token = request.nextUrl.searchParams.get("token")
  if (!token) {
    return NextResponse.redirect(new URL("/", request.nextUrl.origin))
  }

  const redirectParam = request.nextUrl.searchParams.get("redirect") ?? "/"
  const forwardedProto = request.headers.get("x-forwarded-proto")
  const hostHeader = request.headers.get("x-forwarded-host") ?? request.headers.get("host")
  const schemeFromUrl = request.nextUrl.protocol.replace(/:$/, "") || undefined
  const derivedOrigin = hostHeader
    ? `${forwardedProto ?? schemeFromUrl ?? "https"}://${hostHeader}`
    : null
  const configuredAppUrl = env.NEXT_PUBLIC_APP_URL?.trim()
  const isLocalHost =
    configuredAppUrl &&
    (configuredAppUrl.includes("localhost") || configuredAppUrl.includes("127.0.0.1"))

  // Se a APP_URL configurada é localhost, usar o host real do request para evitar redirecionar para 127.0.0.1 em produção.
  const baseOrigin =
    (!configuredAppUrl || isLocalHost) ? derivedOrigin ?? request.nextUrl.origin : configuredAppUrl
  const redirectUrl = new URL(redirectParam, baseOrigin)

  try {
    const session = await createMachineSession(token, true)
    const response = NextResponse.redirect(redirectUrl)

    // Propaga os cookies de sessão do Better Auth (podem vir múltiplos)
    const headersAny = session.headers as unknown as { getSetCookie?: () => string[] }
    let setCookies: string[] = []
    try {
      if (typeof headersAny?.getSetCookie === "function") {
        setCookies = headersAny.getSetCookie() ?? []
      } else {
        const single = session.headers.get("set-cookie")
        if (single) setCookies = [single]
      }
    } catch {
      const single = session.headers.get("set-cookie")
      if (single) setCookies = [single]
    }

    // Converte os Set-Cookie recebidos em cookies do Next (maior compatibilidade)
    const toPairs = (raw: string) => {
      const [nameValue, ...attrs] = raw.split(/;\s*/)
      const [name, ...v] = nameValue.split("=")
      const value = v.join("=")
      const record: Record<string, string | boolean> = { name, value }
      for (const attr of attrs) {
        const [k, ...vv] = attr.split("=")
        const key = k.toLowerCase()
        const val = vv.join("=")
        if (!val && (key === "httponly" || key === "secure")) {
          record[key] = true
        } else if (val) {
          record[key] = val
        }
      }
      return record
    }
    for (const raw of setCookies) {
      const rec = toPairs(raw)
      const name = String(rec.name)
      const value = String(rec.value)
      const options: Parameters<typeof response.cookies.set>[2] = {
        httpOnly: Boolean(rec["httponly"]) || /httponly/i.test(raw),
        secure: /;\s*secure/i.test(raw),
        path: typeof rec["path"] === "string" ? (rec["path"] as string) : "/",
      }
      if (typeof rec["samesite"] === "string") {
        const s = String(rec["samesite"]).toLowerCase() as "lax" | "strict" | "none"
        options.sameSite = s
      }
      if (typeof rec["domain"] === "string") options.domain = rec["domain"] as string
      if (typeof rec["expires"] === "string") options.expires = new Date(rec["expires"] as string)
      if (typeof rec["max-age"] === "string") options.maxAge = Number(rec["max-age"])
      response.cookies.set(name, value, options)
    }

    const machineCookiePayload = {
      machineId: session.machine.id,
      persona: session.machine.persona,
      assignedUserId: session.machine.assignedUserId,
      assignedUserEmail: session.machine.assignedUserEmail,
      assignedUserName: session.machine.assignedUserName,
      assignedUserRole: session.machine.assignedUserRole,
    }
    const encodedContext = Buffer.from(JSON.stringify(machineCookiePayload)).toString("base64url")
    const isSecure = redirectUrl.protocol === "https:"
    response.cookies.set({
      name: "machine_ctx",
      value: encodedContext,
      httpOnly: true,
      sameSite: "lax",
      secure: isSecure,
      path: "/",
      maxAge: 60 * 60 * 24 * 30,
    })

    return response
  } catch (error) {
    if (error instanceof MachineInactiveError) {
      return new NextResponse(INACTIVE_TEMPLATE, {
        status: 423,
        headers: {
          "Content-Type": "text/html; charset=utf-8",
        },
      })
    }
    console.error("[machines.handshake] Falha ao autenticar dispositivo", error)

    const errorUrl = new URL("/machines/auth-error", request.nextUrl.origin)
    errorUrl.searchParams.set("reason", "invalid_token")
    return NextResponse.redirect(errorUrl)
  }
}
