import { getDimcodeUserDir } from './user-cache'

const UPGRADE_TOAST_FILE = 'upgrade-toast.json'

type RuntimeGlobals = typeof globalThis & {
  __DIMCODE_UPGRADE_TOAST__?: (text: string) => void
}

function runtimeGlobals(): RuntimeGlobals {
  return globalThis as RuntimeGlobals
}

export function notifyUpgradeToast(message: string): void {
  const text = String(message ?? '').trim()
  if (!text)
    return

  const handler = runtimeGlobals().__DIMCODE_UPGRADE_TOAST__
  if (typeof handler === 'function') {
    try {
      handler(text)
      return
    }
    catch {
      // fall through to file persistence
    }
  }

  void writeUpgradeToastFile(text)
}

async function writeUpgradeToastFile(message: string): Promise<void> {
  try {
    const [{ mkdir, writeFile }, path] = await Promise.all([
      import('node:fs/promises'),
      import('node:path'),
    ])
    const dir = await getDimcodeUserDir(
      process.env as Record<string, string | undefined>,
    )
    await mkdir(dir, { recursive: true })
    const filePath = path.join(dir, UPGRADE_TOAST_FILE)
    const payload = JSON.stringify({ message, createdAt: Date.now() })
    await writeFile(filePath, payload, 'utf8')
  }
  catch {
    // ignore
  }
}
