/**
 * Google OAuth Signup OTP Verification
 *
 * After user completes Google OAuth and receives OTP,
 * this endpoint verifies the OTP and creates the account.
 *
 * Flow:
 * 1. Verify OTP code
 * 2. Create user account with Google data (email, name, googleId)
 * 3. Mark email as verified (from Google)
 * 4. Create audit log
 * 5. Return success (frontend creates session)
 */

import { NextRequest, NextResponse } from "next/server";
import { validateCSRFToken } from "@/lib/csrf";
import { verifyOTP } from "@/lib/otp-helper";
import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";
import { createId } from "@paralleldrive/cuid2";
import { getDataSource } from "@/lib/data-source";

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, code, fullName, selectedPackage, googleData } = body;

    if (!email || !code) {
      return NextResponse.json(
        { error: "Email and verification code required" },
        { status: 400 },
      );
    }

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

    logger.info("Verifying Google OAuth signup OTP", { email });

    // Verify OTP code
    const otpValid = await verifyOTP(email, code);

    if (!otpValid) {
      logger.warn("Invalid OTP for Google OAuth signup", { email });
      return NextResponse.json(
        { error: "Invalid or expired verification code" },
        { status: 400 },
      );
    }

    logger.info("OTP verified for Google OAuth signup", { email });

    // Check if user already exists — try Convex first if configured
    let userExists = false;
    if (getDataSource("auth") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");
        const cu = (await convexQuery("auth/queries:getUserByEmail", {
          email,
        })) as Record<string, unknown> | null;
        if (cu) userExists = true;
      } catch (error) {
        console.error(
          "[Convex fallback] auth verify-google-signup-otp user lookup:",
          error,
        );
      }
    }

    if (!userExists) {
      const existingUser = await prisma.users.findUnique({
        where: { email },
      });
      if (existingUser) userExists = true;
    }

    if (userExists) {
      logger.warn("User already exists during Google OAuth signup", { email });
      return NextResponse.json(
        { error: "Account already exists. Please log in instead." },
        { status: 409 },
      );
    }

    // Get Google ID from stored data (we'll get it from account linking later)
    // For now, we'll create the user and link Google account when they first sign in

    // Create new user account with Google OAuth data
    const newUserId = createId();
    const now = new Date();
    const newUser = await prisma.users.create({
      data: {
        id: newUserId,
        email,
        name: fullName || googleData.name || "",
        emailVerified: now, // ✅ Email verified via Google OAuth + OTP
        selectedPackage: selectedPackage || null,
        updatedAt: now,
        // Note: googleId will be set when user signs in with Google after account creation
        // We can't set it here because we don't have access to the OAuth account data
      },
    });

    logger.info("User account created from Google OAuth signup", {
      userId: newUser.id,
      email,
    });

    // Mirror new user to Convex
    if (getDataSource("auth") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        await convexMutation("auth/mutations:createUserNoAuth", {
          email,
          name: fullName || googleData.name || "",
          prismaId: newUser.id,
        });
        logger.info("User mirrored to Convex", { userId: newUser.id, email });
      } catch (error) {
        console.error(
          "[Convex fallback] auth verify-google-signup-otp user create:",
          error,
        );
      }
    }

    // Log registration audit event

    logger.info("Google OAuth signup completed", { userId: newUser.id });

    return NextResponse.json({
      success: true,
      userId: newUser.id,
      email: newUser.email,
      name: newUser.name,
    });
  } catch (error) {
    logger.error("Google OAuth OTP verification error", error);

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