import { isReservedSubdomain } from "@/core/config/domains";

const SLUG_MAX_LENGTH = 63;
const SLUG_MIN_LENGTH = 2;

/**
 * Normalize a studio name or user-provided slug into a URL-safe tenant slug.
 */
export function normalizeSlug(input: string): string {
  return input
    .trim()
    .toLowerCase()
    .normalize("NFKD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .replace(/-{2,}/g, "-")
    .slice(0, SLUG_MAX_LENGTH)
    .replace(/-+$/g, "");
}

export function isValidTenantSlug(slug: string): boolean {
  if (slug.length < SLUG_MIN_LENGTH || slug.length > SLUG_MAX_LENGTH) {
    return false;
  }
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) {
    return false;
  }
  if (isReservedSubdomain(slug)) {
    return false;
  }
  return true;
}

/**
 * Generate candidate slugs when the preferred slug is taken.
 * Does NOT overwrite existing tenants.
 */
export function suggestSlugAlternatives(
  baseSlug: string,
  studioName: string,
): string[] {
  const base = normalizeSlug(baseSlug) || normalizeSlug(studioName) || "studio";
  const suggestions = [
    base,
    `${base}-architecture`,
    `${base}-studio`,
    `${base}-architects`,
    normalizeSlug(`${studioName}-studio`),
  ];

  return [...new Set(suggestions.filter(isValidTenantSlug))];
}
