function publicAppUrl(env = process.env) {
  const configured = String(env.PUBLIC_APP_URL || '').trim();
  const domain = String(env.FULL_DOMAIN || '').trim();
  const value = configured || (domain ? `https://${domain}` : '');

  if (!value) {
    throw new Error('PUBLIC_APP_URL or FULL_DOMAIN is required for email links');
  }

  const url = new URL(value);
  const localDevelopment = env.NODE_ENV !== 'production' && ['localhost', '127.0.0.1'].includes(url.hostname);
  if (url.protocol !== 'https:' && !localDevelopment) {
    throw new Error('Public application URL must use HTTPS');
  }

  return url.origin;
}

module.exports = { publicAppUrl };
