import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { checkSubdomainLimiter, rateLimitHeaders } from "@/lib/rate-limit";
import { SUBDOMAIN_REGEX, SUBDOMAIN_MIN_LENGTH, SUBDOMAIN_MAX_LENGTH } from "@/lib/config";

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 GET(req: NextRequest) {
  const ip = clientIp(req);
  const limit = checkSubdomainLimiter.limit(`check-subdomain:${ip}`);
  if (!limit.success) {
    return NextResponse.json(
      { available: false, error: "Премногу обиди. Обидете се повторно подоцна." },
      { status: 429, headers: rateLimitHeaders(limit) }
    );
  }

  const raw = req.nextUrl.searchParams.get("slug") || "";
  const slug = raw.toLowerCase().trim();

  if (
    slug.length < SUBDOMAIN_MIN_LENGTH ||
    slug.length > SUBDOMAIN_MAX_LENGTH ||
    !SUBDOMAIN_REGEX.test(slug)
  ) {
    return NextResponse.json(
      { available: false },
      { headers: { "Cache-Control": "private, max-age=60" } }
    );
  }

  const existing = await prisma.user.findUnique({ where: { subdomain: slug } });

  return NextResponse.json(
    { available: !existing },
    { headers: { "Cache-Control": "private, max-age=60" } }
  );
}
