import { awardPoints } from "../../utils/scoring";
import { addUserCustomDomain, countActiveCustomDomains } from "../../db/domains";
import { getProfile } from "../../db/profile";
import { getPlanLimits } from "../../utils/plan-features";

export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const body = await readBody(event);

  const domain = (body?.domain as string)
    ?.trim()
    .toLowerCase()
    .replace(/^https?:\/\//, "");
  if (
    !domain ||
    !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(
      domain,
    )
  ) {
    throw createError({ statusCode: 400, message: "Ungültige Domain" });
  }

  // Plan-Limit prüfen
  const profile = await getProfile(user.id);
  const limits = getPlanLimits(profile?.plan ?? "free");

  if (limits.customDomains !== Infinity) {
    const activeCount = await countActiveCustomDomains(user.id);
    if (activeCount >= limits.customDomains) {
      throw createError({
        statusCode: 403,
        data: {
          error: "plan_limit",
          resource: "custom_domains",
          current: activeCount,
          limit: limits.customDomains,
        },
      });
    }
  }

  try {
    const data = await addUserCustomDomain(user.id, domain, "manual");

    await awardPoints(user.id, "custom_domain_submitted", { domain }).catch(
      () => {},
    );

    return data;
  } catch (err: any) {
    const msg =
      err.message?.includes("duplicate") || err.code === "P2002"
        ? "Domain bereits vorhanden"
        : err.message ?? "Fehler";
    throw createError({ statusCode: 400, message: msg });
  }
});
