import { SUBSITES, WHITELABELS, type WhitelabelConfig } from '../config.ts';

export interface SubsiteInfo {
  host: string;
  path: string;
  short: string;
}

// Returns normalized host (no port)
function normalizeHost(host: string = ''): string {
  if (!host) return '';
  return host.split(':')[0].toLowerCase();
}

const HOSTS: string[] = Object.keys(SUBSITES || {});

export function getSubsiteByHost(rawHost: string = ''): SubsiteInfo | null {
  const host = normalizeHost(rawHost || '');
  if (!host) return null;
  if (SUBSITES[host]) return { host, path: SUBSITES[host], short: host.split('.')[0] };
  // fallback: if short-name match
  const short = host.split('.')[0];
  const hostKey = HOSTS.find(h => h.split('.')[0] === short);
  if (hostKey) return { host: hostKey, path: SUBSITES[hostKey], short };
  return null;
}

export function getSubsiteFromSignal(signal: string = ''): SubsiteInfo | null {
  if (!signal) return null;
  // signal can be 'req' or 'req.boatson.boats'
  const val = signal.split(':')[0].split('?')[0];
  const short = val.split('.')[0];
  // direct host match
  if (SUBSITES[val]) return { host: val, path: SUBSITES[val], short };
  // short name match
  const hostKey = HOSTS.find(h => h.split('.')[0] === short);
  if (hostKey) return { host: hostKey, path: SUBSITES[hostKey], short };
  return null;
}

export function getSubsiteByPath(path: string = ''): SubsiteInfo | null {
  if (!path) return null;
  // check if path starts with one of the SUBSITES values
  const candidate = Object.entries(SUBSITES || {}).find(([, p]) => path.startsWith(p));
  if (!candidate) return null;
  const [hostKey, p] = candidate;
  return { host: hostKey, path: p, short: hostKey.split('.')[0] };
}

export function isSubsiteHost(rawHost: string = '', shortName: string = ''): boolean {
  const h = getSubsiteByHost(rawHost);
  if (!h) return false;
  if (!shortName) return true;
  return h.short === shortName || h.host === shortName;
}

export function getWhitelabelForHost(rawHost: string = ''): WhitelabelConfig | null {
  const info = getSubsiteByHost(rawHost);
  if (!info) return null;
  return WHITELABELS[info.host] ?? null;
}

export default {
  getSubsiteByHost,
  getSubsiteFromSignal,
  isSubsiteHost,
  getWhitelabelForHost,
};
