#!/usr/bin/env bun
/**
 * Upserts POSTGREST_BASE_URL into .env.example (placeholder) and .env.local (real value).
 * Safe to run multiple times.
 */
import { existsSync, readFileSync, writeFileSync } from 'node:fs'

const POSTGREST_BASE_URL = 'https://views-cx.humand.co'

function upsertVar(content: string, key: string, value: string): string {
  const regex = new RegExp(`^${key}=.*$`, 'm')
  return regex.test(content)
    ? content.replace(regex, `${key}=${value}`)
    : content + (content.endsWith('\n') ? '' : '\n') + `${key}=${value}\n`
}

function patchFile(path: string, value: string): void {
  const content = existsSync(path) ? readFileSync(path, 'utf-8') : ''
  writeFileSync(path, upsertVar(content, 'POSTGREST_BASE_URL', value), 'utf-8')
  console.log(`  ✓ ${path}`)
}

patchFile('.env.example', 'https://views-cx.humand.co')
patchFile('.env.local', POSTGREST_BASE_URL)
