/**
 * Send OTP Endpoint
 *
 * Security features:
 * - Rate limiting (5 requests per 15 minutes per email)
 * - CSRF protection
 * - Input validation and sanitization
 * - Secure logging (no OTP codes in production)
 * - Audit logging
 */

import { NextRequest, NextResponse } from "next/server";
import { generateOTP, sendOTP } from "@/lib/otp-storage";
import {
  withRateLimit,
  rateLimiters,
  getEmailIdentifier,
} from "@/lib/rate-limiter";
import { withCSRF } from "@/lib/csrf";
import { validateEmail, sanitizeInput } from "@/lib/input-validation";
import { logger } from "@/lib/logger";

// Force dynamic rendering to prevent build-time execution
export const dynamic = "force-dynamic";
export const runtime = "nodejs";

async function sendOTPHandler(request: NextRequest) {
  try {
    const body = await request.json();
    const { email, language = "en", purpose = "signup" } = body;

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

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

    // Generate OTP
    const code = generateOTP();

    // Send OTP (stores in Redis with bcrypt hash and sends email)
    const sent = await sendOTP(
      sanitizedEmail,
      code,
      language as "ar" | "en",
      undefined,
      purpose as "login" | "signup" | "reset",
    );

    if (!sent) {
      return NextResponse.json(
        { error: "Failed to send OTP. Please try again." },
        { status: 500 },
      );
    }

    // SECURITY: NEVER return OTP code in response
    // For development testing, check console logs
    return NextResponse.json(
      {
        success: true,
        message:
          "Verification code sent successfully. Please check your email.",
      },
      { status: 200 },
    );
  } catch (error) {
    logger.error("Send OTP API error", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}

// Apply rate limiting (5 requests per 15 min per IP) and CSRF protection
// Note: Using IP-based limiting to avoid request body consumption issues
export const POST = withCSRF(
  withRateLimit(sendOTPHandler, rateLimiters.otpSend),
);
