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

const MAIN_DOMAIN = process.env.MAIN_DOMAIN || "alfrednobel.edudeploy.com";

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const domain = searchParams.get("domain");

  if (!domain) {
    return NextResponse.json({ ok: false }, { status: 400 });
  }

  if (domain === MAIN_DOMAIN || domain === `headscale.${MAIN_DOMAIN}`) {
    return NextResponse.json({ ok: true });
  }

  if (!domain.endsWith(`.${MAIN_DOMAIN}`)) {
    return NextResponse.json({ ok: false }, { status: 400 });
  }

  const subdomain = domain.replace(`.${MAIN_DOMAIN}`, "");
  const instance = await prisma.instance.findUnique({
    where: { id: subdomain },
  });

  return NextResponse.json({ ok: !!instance });
}
