/**
 * Verify OTP and Activate Subscription Endpoint
 *
 * This endpoint combines OTP verification with subscription activation.
 * It's used during the signup flow after Stripe payment is completed.
 *
 * Security features:
 * - Rate limiting (5 attempts per 15 minutes)
 * - CSRF protection
 * - Input validation and sanitization
 * - Audit logging
 */

import { NextRequest, NextResponse } from "next/server";
import { verifyOTP, getRemainingAttempts } from "@/lib/otp-storage";
import { withRateLimit, rateLimiters } from "@/lib/rate-limiter";
import { withCSRF } from "@/lib/csrf";
import {
  validateEmail,
  validateOTPCode,
  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 verifyOTPAndActivateHandler(request: NextRequest) {
  try {
    const body = await request.json();
    const { email, otpCode, stripeSessionId } = body;

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

    // Validate OTP code format
    const codeValidation = validateOTPCode(otpCode);
    if (!codeValidation.valid) {
      return NextResponse.json(
        { error: codeValidation.error },
        { status: 400 },
      );
    }

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

    // Check remaining attempts
    const remaining = await getRemainingAttempts(sanitizedEmail);
    if (remaining <= 0) {
      return NextResponse.json(
        {
          error:
            "Maximum verification attempts exceeded. Please request a new code.",
        },
        { status: 429 },
      );
    }

    // 1. Verify OTP
    const isValid = await verifyOTP(sanitizedEmail, sanitizedCode);
    if (!isValid) {
      const newRemaining = await getRemainingAttempts(sanitizedEmail);
      return NextResponse.json(
        {
          error: "Invalid or expired verification code",
          remainingAttempts: newRemaining,
        },
        { status: 401 },
      );
    }

    // 2. 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-otp-and-activate:", error);
      }
    }

    // 3. 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 after OTP verification", {
            userId: user.id,
            subscriptionId,
          });
        }
      } catch (stripeError) {
        logger.error("Failed to activate subscription", stripeError);
        // Don't fail the whole request - email is still verified
      }
    }

    // 4. 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: "OTP verification successful, subscription activated",
        success: true,
        ip:
          request.headers.get("x-forwarded-for") ||
          request.headers.get("x-real-ip") ||
          "unknown",
        userAgent: request.headers.get("user-agent") || undefined,
      },
    });

    return NextResponse.json({
      success: true,
      userId: user.id,
      message: "Email verified and subscription activated",
    });
  } catch (error) {
    logger.error("Verify OTP and Activate API error", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}

// Apply rate limiting and CSRF protection
export const POST = withCSRF(
  withRateLimit(verifyOTPAndActivateHandler, rateLimiters.otpVerify),
);
