import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { registrations } from '@/lib/db/schema';
import { registrationSchema } from '@/lib/validations/registration';

const ipMap = new Map<string, { count: number; resetAt: number }>();
const emailMap = new Map<string, number>();

const IP_LIMIT      = 3;
const IP_WINDOW_MS  = 60 * 60 * 1000; 
const EMAIL_COOL_MS = 10 * 60 * 1000; 

function getRealIp(req: NextRequest): string {
  return (
    req.headers.get('x-forwarded-for')?.split(',')[0].trim() ??
    req.headers.get('x-real-ip') ??
    'unknown'
  );
}

function checkIpLimit(ip: string): boolean {
  const now = Date.now();
  const entry = ipMap.get(ip);
  if (!entry || now > entry.resetAt) {
    ipMap.set(ip, { count: 1, resetAt: now + IP_WINDOW_MS });
    return false; // not limited
  }
  if (entry.count >= IP_LIMIT) return true;
  entry.count += 1;
  return false;
}

export async function POST(req: NextRequest) {
  const ip = getRealIp(req);

  if (checkIpLimit(ip)) {
    return NextResponse.json(
      { success: false, error: 'Too many registrations from this network. Please try again later.' },
      { status: 429 }
    );
  }

  let rawBody: unknown;
  try {
    rawBody = await req.json();
  } catch {
    return NextResponse.json({ success: false, error: 'Invalid request.' }, { status: 400 });
  }

  if (
    typeof rawBody === 'object' &&
    rawBody !== null &&
    '_hp' in rawBody &&
    (rawBody as Record<string, unknown>)['_hp']
  ) {
    return NextResponse.json({ success: true });
  }

  const parsed = registrationSchema.safeParse(rawBody);
  if (!parsed.success) {
    return NextResponse.json(
      { success: false, error: parsed.error.errors[0]?.message ?? 'Invalid data.' },
      { status: 422 }
    );
  }

  const data = parsed.data;

  const emailKey = data.email.toLowerCase();
  const lastSub  = emailMap.get(emailKey);
  if (lastSub && Date.now() - lastSub < EMAIL_COOL_MS) {
    return NextResponse.json(
      { success: false, error: 'This email was recently used. Please wait a few minutes.' },
      { status: 429 }
    );
  }

  try {
    await db.insert(registrations).values({
      fullName:       data.fullName,
      email:          data.email,
      phone:          data.phone,
      gender:         data.gender,
      ageRange:       data.ageRange,
      educationLevel: data.educationLevel,
      institution:    data.institution,
      stack:          data.stack,
      motivation:     data.motivation,
      heardFrom:      data.heardFrom,
      referralCode:   data.referralCode || null,
    });

    emailMap.set(emailKey, Date.now());

    return NextResponse.json({ success: true });
  } catch (err: unknown) {
    const code =
      (err as { code?: string })?.code ??
      (err as { cause?: { code?: string } })?.cause?.code;

    if (code === '23505') {
      return NextResponse.json(
        { success: false, error: 'This email address has already been registered.' },
        { status: 409 }
      );
    }

    console.error('Registration DB error:', err);
    return NextResponse.json(
      { success: false, error: 'Something went wrong. Please try again later.' },
      { status: 500 }
    );
  }
}