import { NextResponse } from "next/server";
import { sql } from "@/db";
import { logAudit } from "@/lib/audit";

export const dynamic = "force-dynamic";

const APP_URL = process.env.NEXT_PUBLIC_APP_URL || "https://tia.manohargupta.com";

// GET — the link target from the verification email.
export async function GET(request: Request) {
  const token = new URL(request.url).searchParams.get("token");
  if (!token) {
    return NextResponse.redirect(new URL("/login?error=verify", APP_URL));
  }

  try {
    // Single-use, unexpired lookup (mirrors reset-confirm).
    const rows = await sql`
      SELECT id, user_id FROM email_verifications
      WHERE token = ${token} AND expires_at > NOW() AND used_at IS NULL
      LIMIT 1
    `;
    if (rows.length === 0) {
      return NextResponse.redirect(new URL("/login?error=verify", APP_URL));
    }

    const verifyId = rows[0].id;
    const userId = rows[0].user_id;

    // Mark verified and burn the token.
    await sql`UPDATE users SET email_verified = NOW() WHERE id = ${userId}`;
    await sql`UPDATE email_verifications SET used_at = NOW() WHERE id = ${verifyId}`;

    // Clicking the link proves email ownership -> log them in now.
    const sessionToken = crypto.randomUUID();
    const expires = new Date();
    expires.setDate(expires.getDate() + 30);
    await sql`
      INSERT INTO sessions (session_token, user_id, expires)
      VALUES (${sessionToken}, ${userId}, ${expires.toISOString()})
    `;
    await logAudit({ userId, action: "email_verified", request });

    const response = NextResponse.redirect(new URL("/onboarding", APP_URL));
    response.cookies.set("tia_session", sessionToken, {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      maxAge: 60 * 60 * 24 * 30,
      path: "/",
    });
    return response;
  } catch (e) {
    console.error("Verify email error:", e);
    return NextResponse.redirect(new URL("/login?error=verify", APP_URL));
  }
}
