import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { prisma } from "@/lib/prisma";
import { validateCodeLimiter, rateLimitHeaders } from "@/lib/rate-limit";

function clientIp(req: NextRequest): string {
  const fwd = req.headers.get("x-forwarded-for");
  if (fwd) return fwd.split(",")[0].trim();
  return req.headers.get("x-real-ip") || "unknown";
}

export async function POST(req: NextRequest) {
  const ip = clientIp(req);
  const limit = validateCodeLimiter.limit(`validate-code:${ip}`);
  if (!limit.success) {
    return NextResponse.json(
      { error: "Премногу обиди. Обидете се повторно подоцна." },
      { status: 429, headers: rateLimitHeaders(limit) }
    );
  }

  const { userId } = await auth();
  if (!userId) {
    return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
  }

  try {
    const { code } = await req.json();
    if (!code?.trim()) {
      return NextResponse.json({ error: "Кодот е задолжителен" }, { status: 400 });
    }

    const normalizedCode = code.trim().toUpperCase();
    if (!/^[A-F0-9]{12}$/.test(normalizedCode)) {
      return NextResponse.json({ valid: false, error: "Невалиден код" });
    }

    const existing = await prisma.code.findUnique({ where: { code: normalizedCode } });
    if (!existing) {
      return NextResponse.json({ valid: false, error: "Невалиден код" });
    }
    if (existing.usedByUserId) {
      return NextResponse.json({ valid: false, error: "Кодот е веќе искористен" });
    }

    const alreadyUsed = await prisma.code.findFirst({
      where: { usedByUserId: userId },
    });
    if (alreadyUsed) {
      return NextResponse.json({ valid: false, error: "Веќе имате искористено код" });
    }

    const updated = await prisma.code.updateMany({
      where: { id: existing.id, usedByUserId: null },
      data: { usedByUserId: userId, usedAt: new Date() },
    });

    if (updated.count === 0) {
      return NextResponse.json({ valid: false, error: "Кодот е веќе искористен" });
    }

    return NextResponse.json({ valid: true });
  } catch (error) {
    console.error("Validate code error:", error);
    return NextResponse.json({ error: "Внатрешна грешка на серверот" }, { status: 500 });
  }
}
