import type { TenantSummary } from "../../../lib/adminApi";

export type DomainConflict = {
  domain: string;
  tenant: TenantSummary;
};

export type ServerDomainConflict = {
  domain: string;
  tenantId?: string;
  tenantName?: string;
  tenantSlug?: string;
};

export function normalizeDomainTokens(value: string): string[] {
  const seen = new Set<string>();
  const tokens: string[] = [];
  for (const raw of value.split(/[,\s;]+/)) {
    const token = raw.trim().toLowerCase();
    if (!token || seen.has(token)) {
      continue;
    }
    seen.add(token);
    tokens.push(token);
  }
  return tokens;
}

export function findDomainConflict(
  domain: string,
  tenants: TenantSummary[] = [],
  currentTenantId?: string,
): DomainConflict | null {
  const normalized = domain.trim().toLowerCase();
  if (!normalized) {
    return null;
  }

  for (const tenant of tenants) {
    if (tenant.id === currentTenantId) {
      continue;
    }
    const domains = tenant.domains ?? [];
    if (domains.some((item) => item.trim().toLowerCase() === normalized)) {
      return { domain: normalized, tenant };
    }
  }
  return null;
}

export function formatDomainConflictMessage(
  conflict: DomainConflict | ServerDomainConflict,
): string {
  const tenantName =
    "tenant" in conflict
      ? conflict.tenant.name
      : conflict.tenantName ||
        conflict.tenantSlug ||
        conflict.tenantId ||
        "다른";
  return `${conflict.domain} 도메인은 ${tenantName} 테넌트에 이미 설정되어 있습니다. 그래도 현재 테넌트에도 추가하시겠습니까?`;
}
