import { submitDomainForReview } from "../../../db/domains";
import { getProfile } from "../../../db/profile";
import { getPlanLimits } from "../../../utils/plan-features";
import { usePrisma } from "../../../utils/prisma";

export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const id = getRouterParam(event, "id");
  if (!id) throw createError({ statusCode: 400, message: "ID fehlt" });

  // Only Pro/Legend can submit
  const profile = await getProfile(user.id);
  const plan = profile?.plan ?? "free";
  const limits = getPlanLimits(plan);
  if (!limits.domainRefill) {
    throw createError({
      statusCode: 403,
      message: "Nur Pro-User können Domains einreichen",
    });
  }

  const db = usePrisma();
  // Verify ownership + status
  const existing = await db.userCustomDomain.findFirst({
    where: { id, userId: user.id },
    select: { id: true, domain: true, status: true },
  });
  if (!existing)
    throw createError({ statusCode: 404, message: "Domain nicht gefunden" });
  if (existing.status !== "active" && existing.status !== "rejected") {
    throw createError({
      statusCode: 409,
      message: "Domain wurde bereits eingereicht oder genehmigt",
    });
  }

  // Tier-Routing:
  //  - Pro:    Community-Post mit Voting-Flow erstellen
  //  - Legend: KEIN Post — Domain landet direkt in der Admin-Queue zur manuellen Prüfung
  let postId: string | null = null;
  if (plan === "pro") {
    const postContent = `🛡️ Domain-Vorschlag: **${existing.domain}**\n\nIch schlage vor, diese Domain zur globalen ReBreak-Sperrliste hinzuzufügen. Stimme ab: Sollte **${existing.domain}** global gesperrt werden?`;
    const post = await db.communityPost.create({
      data: {
        userId: user.id,
        category: "domain_vote",
        content: postContent,
      },
      select: { id: true },
    });
    postId = post.id;
  }

  const { submission } = await submitDomainForReview(
    user.id,
    id,
    plan as "free" | "pro" | "legend",
    postId ?? undefined,
  );

  return {
    ok: true,
    postId,
    submissionId: submission.id,
    domain: existing.domain,
    route: plan === "legend" ? "admin_direct" : "community_vote",
  };
});
