import { NextResponse } from "next/server";
import { addMcRegistration } from "@/lib/db";
import { checkRateLimit, getClientIp } from "@/lib/rateLimit";
import { sanitizeName, sanitizePhone, sanitizeHandle, sanitizeText } from "@/lib/validation";

export async function POST(request: Request) {
  const ip = getClientIp(request);
  if (!checkRateLimit(ip, 5, 60_000)) {
    return NextResponse.json(
      { error: "Слишком много запросов. Попробуйте через минуту." },
      { status: 429 }
    );
  }

  try {
    const body = await request.json();
    const { masterClassTitle, name, phone, instagram, telegram } = body;

    const cleanTitle = sanitizeText(masterClassTitle, 200);
    if (!cleanTitle) {
      return NextResponse.json({ error: "masterClassTitle is required" }, { status: 400 });
    }

    const cleanName = sanitizeName(name);
    if (!cleanName) {
      return NextResponse.json({ error: "Имя обязательно" }, { status: 400 });
    }

    const cleanPhone = sanitizePhone(phone);
    if (!cleanPhone) {
      return NextResponse.json({ error: "Телефон обязателен" }, { status: 400 });
    }

    const id = addMcRegistration(
      cleanTitle,
      cleanName,
      sanitizeHandle(instagram) ?? "",
      sanitizeHandle(telegram),
      cleanPhone
    );

    return NextResponse.json({ ok: true, id });
  } catch (err) {
    console.error("[master-class-register] POST error:", err);
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
}
