/**
 * The ONE base-app touch-point — PLAN_RELAY_AGENT T17 (INDEX §0, EXPLORE §3 "Zero code change").
 * APPENDS `https://<subdomain>.term.<domain>` to the base app's ALLOWED_ORIGINS env (idempotent),
 * as CONFIG — NO `src/` code edit. AUGMENTS, never weakens, the Origin/CSWSH check: existing
 * origins are always preserved (EXPLORE §3 "do not weaken the check").
 */
import { existsSync, readFileSync, writeFileSync } from 'node:fs'

export interface OriginFsDeps {
  exists(path: string): boolean
  read(path: string): string
  write(path: string, content: string): void
}

const defaultFs: OriginFsDeps = {
  exists: existsSync,
  read: (p) => readFileSync(p, 'utf8'),
  write: (p, c) => writeFileSync(p, c),
}

/** Compose the subdomain origin the base app must trust. */
export function subdomainOrigin(subdomain: string, domain: string): string {
  return `https://${subdomain}.term.${domain}`
}

const KEY = 'ALLOWED_ORIGINS'

function upsertOriginLine(content: string, origin: string): string {
  const lines = content.length === 0 ? [] : content.split('\n')
  let found = false
  const next = lines.map((line) => {
    if (!line.startsWith(`${KEY}=`)) return line
    found = true
    const current = line.slice(KEY.length + 1)
    const origins = current.split(',').map((s) => s.trim()).filter((s) => s.length > 0)
    if (origins.includes(origin)) return line // idempotent — already trusted
    return `${KEY}=${[...origins, origin].join(',')}`
  })
  if (!found) next.push(`${KEY}=${origin}`)
  return next.join('\n')
}

/**
 * Idempotently append the subdomain origin to ALLOWED_ORIGINS in `baseAppEnvPath`. Never removes an
 * existing origin. Creates the file/line if absent.
 */
export function ensureAllowedOrigin(
  baseAppEnvPath: string,
  subdomain: string,
  domain: string,
  fs: OriginFsDeps = defaultFs,
): void {
  const origin = subdomainOrigin(subdomain, domain)
  const existing = fs.exists(baseAppEnvPath) ? fs.read(baseAppEnvPath) : ''
  const updated = upsertOriginLine(existing, origin)
  fs.write(baseAppEnvPath, updated.endsWith('\n') ? updated : `${updated}\n`)
}
