import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { prisma } from "@/lib/prisma";

export async function POST(req: NextRequest) {
  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();

    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: "Веќе имате искористено код" });
    }

    await prisma.code.update({
      where: { id: existing.id },
      data: { usedByUserId: userId, usedAt: new Date() },
    });

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