import {
  getDevPlatformHosts,
  getPlatformAdminHost,
  getPlatformApiHost,
  getPlatformAppHost,
  getPlatformRootDomain,
  hostnameWithoutPort,
  isReservedSubdomain,
  normalizeHostname,
} from "@/core/config/domains";
import type { HostKind } from "@/core/tenant/types";

/**
 * Parse hostname into a host kind WITHOUT database access.
 * Does not resolve tenant identity — only classifies the request host.
 */
export function classifyHostname(rawHostname: string): HostKind {
  const hostname = normalizeHostname(rawHostname);
  const hostNoPort = hostnameWithoutPort(hostname);
  const root = getPlatformRootDomain();
  const appHost = hostnameWithoutPort(getPlatformAppHost());
  const adminHost = hostnameWithoutPort(getPlatformAdminHost());
  const apiHost = hostnameWithoutPort(getPlatformApiHost());

  const devHosts = getDevPlatformHosts().map(hostnameWithoutPort);

  if (
    hostNoPort === "localhost" ||
    hostNoPort === "127.0.0.1" ||
    isIpAddress(hostNoPort) ||
    devHosts.includes(hostNoPort) ||
    hostNoPort === root ||
    hostNoPort === `www.${root}`
  ) {
    return { kind: "platform" };
  }

  if (hostNoPort === appHost) {
    return { kind: "app" };
  }

  if (hostNoPort === adminHost) {
    return { kind: "admin" };
  }

  if (hostNoPort === apiHost) {
    return { kind: "api" };
  }

  // Local multi-tenant simulation: mukhsin.localhost
  if (hostNoPort.endsWith(".localhost")) {
    const slug = hostNoPort.replace(/\.localhost$/, "");
    if (!slug || isReservedSubdomain(slug) || slug.includes(".")) {
      return { kind: "unknown" };
    }
    return { kind: "tenant_subdomain", slug };
  }

  // Production subdomain: mukhsin.archi.com
  if (hostNoPort.endsWith(`.${root}`)) {
    const slug = hostNoPort.slice(0, -(root.length + 1));
    if (!slug || slug.includes(".")) {
      return { kind: "unknown" };
    }
    if (isReservedSubdomain(slug)) {
      // Reserved system hosts already handled above; treat leftovers as unknown
      return { kind: "unknown" };
    }
    return { kind: "tenant_subdomain", slug };
  }

  // Anything else is a potential custom domain
  if (hostNoPort.includes(".")) {
    return { kind: "custom_domain", domain: hostNoPort };
  }

  return { kind: "unknown" };
}

function isIpAddress(host: string): boolean {
  // IPv4
  if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host)) return true;
  // IPv6 (simplified)
  if (host.includes(":")) return true;
  return false;
}
