/**
 * Verify Email Only Endpoint (Development Mode)
 *
 * Simplified verification that bypasses Redis OTP storage.
 * Used for testing when OTP codes are generated and validated client-side.
 *
 * ⚠️ DEVELOPMENT ONLY: This endpoint trusts client validation
 * Production should use verify-otp-and-activate with server-side OTP validation
 */

import { NextRequest, NextResponse } from "next/server";
import { withCSRF } from "@/lib/csrf";
import { validateEmail, sanitizeInput } from "@/lib/input-validation";
import { stripe } from "@/lib/stripe";
import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";

// Force dynamic rendering
export const dynamic = "force-dynamic";
export const runtime = "nodejs";

async function verifyEmailOnlyHandler(request: NextRequest) {
  try {
    const body = await request.json();
    const { email, stripeSessionId } = body;

    // Validate email
    const emailValidation = validateEmail(email);
    if (!emailValidation.valid) {
      return NextResponse.json(
        { error: emailValidation.error },
        { status: 400 },
      );
    }

    const sanitizedEmail = sanitizeInput(email).toLowerCase();

    // Mark email as verified in database
    const user = await prisma.users.update({
      where: { email: sanitizedEmail },
      data: { emailVerified: new Date() },
    });

    // Mirror email verification to Convex
    if (getDataSource("auth") === "convex") {
      try {
        const { convexQuery, convexMutation } =
          await import("@/lib/convex-client");
        const convexUser = (await convexQuery("auth/queries:getUserByEmail", {
          email: sanitizedEmail,
        })) as Record<string, unknown> | null;
        if (convexUser && convexUser._id) {
          await convexMutation("auth/mutations:updateUserNoAuth", {
            userId: convexUser._id as any,
          });
        }
      } catch (error) {
        console.error("[Convex fallback] auth verify-email-only:", error);
      }
    }

    // Activate subscription if Stripe session ID provided
    if (stripeSessionId) {
      try {
        const session =
          await stripe.checkout.sessions.retrieve(stripeSessionId);
        const subscriptionId = session.subscription as string;

        if (subscriptionId) {
          // Update subscription status from pending_verification to trialing
          await prisma.subscriptions.updateMany({
            where: {
              stripeSubscriptionId: subscriptionId,
              userId: user.id,
            },
            data: {
              status: "trialing", // Activate trial period
            },
          });

          logger.info("Subscription activated (dev mode)", {
            userId: user.id,
            subscriptionId,
          });
        }
      } catch (stripeError) {
        logger.error("Failed to activate subscription", stripeError);
        // Don't fail the whole request - email is still verified
      }
    }

    // Create audit log
    await prisma.audit_logs.create({
      data: {
        id: crypto.randomUUID(), // Generate unique ID for audit log
        userId: user.id,
        type: "email_verified",
        action: "Email verified (development mode - client-side OTP)",
        success: true,
        ip:
          request.headers.get("x-forwarded-for") ||
          request.headers.get("x-real-ip") ||
          "unknown",
        userAgent: request.headers.get("user-agent") || undefined,
        metadata: {
          mode: "development",
          method: "client_side_otp",
        },
      },
    });

    logger.info("[DEV] Email verified without Redis OTP check", {
      email: sanitizedEmail,
      userId: user.id,
    });

    return NextResponse.json({
      success: true,
      userId: user.id,
      message: "Email verified successfully (dev mode)",
    });
  } catch (error) {
    logger.error("Verify Email Only API error", error);
    return NextResponse.json({ error: "Verification failed" }, { status: 500 });
  }
}

// Apply CSRF protection
export const POST = withCSRF(verifyEmailOnlyHandler);
