function normalizeEnvValue(value: unknown) {
  return String(value || '').trim().replace(/\/$/, '')
}

function tryParseUrl(value: string) {
  const trimmed = normalizeEnvValue(value)
  if (!trimmed) return null
  try {
    return new URL(trimmed)
  } catch {
    return null
  }
}

function isLoopbackHostname(hostname: string) {
  const normalized = hostname.trim().toLowerCase()
  return normalized === 'localhost'
    || normalized === '127.0.0.1'
    || normalized === '::1'
    || normalized === '[::1]'
}

function normalizeLoopbackOrigin(configuredOrigin: string, locationOrigin: string) {
  if (!configuredOrigin || !locationOrigin) return configuredOrigin

  try {
    const configured = new URL(configuredOrigin)
    const current = new URL(locationOrigin)
    const loopbackHosts = new Set(['localhost', '127.0.0.1'])

    if (
      loopbackHosts.has(configured.hostname)
      && loopbackHosts.has(current.hostname)
      && configured.protocol === current.protocol
      && configured.port === current.port
    ) {
      return normalizeEnvValue(locationOrigin)
    }
  } catch {
    return configuredOrigin
  }

  return configuredOrigin
}

export interface AuthEnvLike {
  [key: string]: string | number | undefined
  VITE_SUPERTOKENS_API_DOMAIN?: string
  VITE_SUPERTOKENS_WEBSITE_DOMAIN?: string
  VITE_SUPERTOKENS_API_BASE_PATH?: string
  VITE_SUPERTOKENS_WEBSITE_BASE_PATH?: string
  VITE_AUTH_API_BASE_URL?: string
  VITE_AUTH_API_TIMEOUT_MS?: string | number
}

export interface AuthRuntimeConfig {
  superTokensApiDomain: string
  superTokensWebsiteDomain: string
  superTokensApiBasePath: string
  superTokensWebsiteBasePath: string
  authApiBaseUrl: string
  authApiTimeoutMs: number
}

export function getAuthRuntimeConfig(
  env: Partial<AuthEnvLike> = import.meta.env as Partial<AuthEnvLike>,
  options?: { locationOrigin?: string },
): AuthRuntimeConfig {
  const locationOrigin = normalizeEnvValue(
    options?.locationOrigin ?? (typeof window !== 'undefined' ? window.location.origin : ''),
  )

  return {
    superTokensApiDomain: normalizeLoopbackOrigin(
      normalizeEnvValue(env.VITE_SUPERTOKENS_API_DOMAIN),
      locationOrigin,
    ),
    superTokensWebsiteDomain: normalizeLoopbackOrigin(
      normalizeEnvValue(env.VITE_SUPERTOKENS_WEBSITE_DOMAIN),
      locationOrigin,
    ),
    superTokensApiBasePath: normalizeEnvValue(env.VITE_SUPERTOKENS_API_BASE_PATH) || '/auth',
    superTokensWebsiteBasePath: normalizeEnvValue(env.VITE_SUPERTOKENS_WEBSITE_BASE_PATH) || '/auth',
    authApiBaseUrl: normalizeLoopbackOrigin(
      normalizeEnvValue(env.VITE_AUTH_API_BASE_URL),
      locationOrigin,
    ),
    authApiTimeoutMs: Math.max(1000, Number(env.VITE_AUTH_API_TIMEOUT_MS || 8000)),
  }
}

export function validateAuthRuntimeConfig(
  env?: Partial<AuthEnvLike>,
): { ready: boolean; missing: string[]; warnings: string[] } {
  const config = getAuthRuntimeConfig(env ?? (import.meta.env as Partial<AuthEnvLike>))
  const missing: string[] = []
  if (!config.superTokensApiDomain) missing.push('VITE_SUPERTOKENS_API_DOMAIN')
  if (!config.superTokensWebsiteDomain) missing.push('VITE_SUPERTOKENS_WEBSITE_DOMAIN')

  const warnings: string[] = []
  if (!config.authApiBaseUrl) {
    warnings.push('VITE_AUTH_API_BASE_URL not configured; same-origin auth fallback remains active.')
  }

  const apiUrl = tryParseUrl(config.superTokensApiDomain)
  const websiteUrl = tryParseUrl(config.superTokensWebsiteDomain)
  const authApiUrl = tryParseUrl(config.authApiBaseUrl)

  if (apiUrl && isLoopbackHostname(apiUrl.hostname)) {
    warnings.push('VITE_SUPERTOKENS_API_DOMAIN still targets a loopback/local-development origin.')
  }
  if (websiteUrl && isLoopbackHostname(websiteUrl.hostname)) {
    warnings.push('VITE_SUPERTOKENS_WEBSITE_DOMAIN still targets a loopback/local-development origin.')
  }
  if (authApiUrl && isLoopbackHostname(authApiUrl.hostname)) {
    warnings.push('VITE_AUTH_API_BASE_URL still targets a loopback/local-development origin.')
  }

  if (apiUrl && !isLoopbackHostname(apiUrl.hostname) && apiUrl.protocol !== 'https:') {
    warnings.push('VITE_SUPERTOKENS_API_DOMAIN uses HTTP on a non-loopback origin; use HTTPS before public launch.')
  }
  if (websiteUrl && !isLoopbackHostname(websiteUrl.hostname) && websiteUrl.protocol !== 'https:') {
    warnings.push('VITE_SUPERTOKENS_WEBSITE_DOMAIN uses HTTP on a non-loopback origin; use HTTPS before public launch.')
  }
  if (authApiUrl && !isLoopbackHostname(authApiUrl.hostname) && authApiUrl.protocol !== 'https:') {
    warnings.push('VITE_AUTH_API_BASE_URL uses HTTP on a non-loopback origin; use HTTPS before public launch.')
  }

  if (config.authApiBaseUrl && config.superTokensApiDomain && config.authApiBaseUrl !== config.superTokensApiDomain) {
    warnings.push('VITE_AUTH_API_BASE_URL differs from VITE_SUPERTOKENS_API_DOMAIN; verify both point at the same auth backend.')
  }

  return {
    ready: missing.length === 0,
    missing,
    warnings,
  }
}
