const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);

export function getSiteOrigin(): URL {
  const configured = process.env.SITE_ORIGIN;
  if (!configured) {
    if (process.env.NODE_ENV !== 'production') return new URL('http://localhost:3000');
    throw new Error('SITE_ORIGIN is required in production. No canonical domain is approved yet.');
  }

  const origin = new URL(configured);
  if (origin.pathname !== '/' || origin.search || origin.hash) {
    throw new Error('SITE_ORIGIN must contain only scheme and host.');
  }
  if (
    process.env.NODE_ENV === 'production' &&
    origin.protocol !== 'https:' &&
    !LOOPBACK_HOSTS.has(origin.hostname)
  ) {
    throw new Error('SITE_ORIGIN must use HTTPS in production.');
  }
  return origin;
}
