/**
 * Google OAuth Signup Callback Handler
 *
 * This endpoint is called after Google OAuth returns to our app during signup.
 * It extracts user info from the session, sends OTP, and prepares for verification.
 *
 * Flow:
 * 1. User completes Google OAuth
 * 2. NextAuth creates temporary session with Google data
 * 3. This endpoint reads that data, sends OTP
 * 4. Stores Google info for later account creation
 * 5. Returns success → frontend redirects to verify page
 */

import { NextRequest, NextResponse } from "next/server";
import { validateCSRFToken } from "@/lib/csrf";
import { sendOTP } from "@/lib/otp-storage";
import { logger } from "@/lib/logger";

export async function POST(req: NextRequest) {
  try {
    // Validate CSRF token
    const csrfValid = validateCSRFToken(req);
    if (!csrfValid) {
      return NextResponse.json(
        { error: "Invalid CSRF token" },
        { status: 403 },
      );
    }

    const body = await req.json();
    const { email, name, googleId, language } = body;

    if (!email || !name || !googleId) {
      return NextResponse.json(
        { error: "Google user data required" },
        { status: 400 },
      );
    }

    logger.info("Google OAuth signup - sending OTP", { email, name });

    // Send OTP to the email from Google
    await sendOTP(email, language || "en");

    logger.info("OTP sent to Google OAuth user", { email });

    // Return success
    return NextResponse.json({
      success: true,
      message:
        language === "ar"
          ? "تم إرسال رمز التحقق إلى بريدك الإلكتروني"
          : "Verification code sent to your email",
    });
  } catch (error) {
    logger.error("Google OAuth signup error", error);

    return NextResponse.json(
      {
        error:
          error instanceof Error
            ? error.message
            : "Failed to send verification code",
      },
      { status: 500 },
    );
  }
}
