/**
 * WhatsApp OAuth State Token (CSRF Protection)
 *
 * GET /api/integrations/whatsapp/oauth/state
 *
 * Generates a random state token for the WhatsApp Embedded Signup OAuth flow,
 * stores it in an HttpOnly cookie, and returns it to the caller so the
 * frontend can pass it to `FB.login()`. The callback route must then verify
 * that the state in the POST body matches the cookie before processing the
 * authorization code — this protects against CSRF on the OAuth exchange.
 */

import { NextRequest, NextResponse } from "next/server";
import crypto from "crypto";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { applyRateLimit, rateLimiters } from "@/lib/rate-limiter";
import { logger } from "@/lib/logger";

const STATE_COOKIE_NAME = "wa-oauth-state";
const STATE_TTL_SECONDS = 600; // 10 minutes

export async function GET(request: NextRequest) {
  // Rate limit (reuses the auth-general limiter since this is an auth-adjacent flow)
  const rateLimitResponse = await applyRateLimit(
    request,
    rateLimiters.authGeneral,
  );
  if (rateLimitResponse) return rateLimitResponse;

  // Require an authenticated user — state tokens should only ever be issued
  // to logged-in sessions launching the OAuth popup from our UI.
  const user = await getAuthenticatedUser(request, auth);
  if (!user) {
    return NextResponse.json(
      { success: false, error: "Unauthorized" },
      { status: 401 },
    );
  }

  // Generate a cryptographically random state token.
  const state = crypto.randomUUID();

  const response = NextResponse.json({ success: true, state });

  // Store the state in an HttpOnly cookie so it cannot be read by JS (XSS
  // protection). The frontend receives the token value in the response body
  // and uses it as the OAuth state parameter; the callback compares the body
  // value to the cookie value.
  response.cookies.set(STATE_COOKIE_NAME, state, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    maxAge: STATE_TTL_SECONDS,
    path: "/",
  });

  logger.info("WhatsApp OAuth state generated", { userId: user.userId });

  return response;
}
