#!/usr/bin/env bun
/**
 * Adds the PostgREST dev proxy to vite.config.ts.
 * Safe to run multiple times — exits 0 with no changes if already patched.
 */
import { readFileSync, writeFileSync } from 'node:fs'

const VITE_CONFIG = 'vite.config.ts'
const MARKER = '/api/postgrest'

const PROXY_BLOCK = `
  server: {
    proxy: {
      '/api/postgrest': {
        target: 'http://localhost:3000',
        changeOrigin: true,
      },
    },
  },`

const content = readFileSync(VITE_CONFIG, 'utf-8')

if (content.includes(MARKER)) {
  console.log('vite.config.ts already has PostgREST proxy — skipping.')
  process.exit(0)
}

if (content.includes('proxy:')) {
  console.error(
    'NEEDS_MANUAL_MERGE: vite.config.ts already has a proxy block. ' +
    'Add the following entry inside the existing proxy object:\n\n' +
    "  '/api/postgrest': {\n" +
    "    target: 'http://localhost:3000',\n" +
    "    changeOrigin: true,\n" +
    '  },',
  )
  process.exit(2)
}

// Insert server block right after `plugins: [react()],`
const patched = content.replace(
  /( *plugins: \[react\(\)\],)/,
  `$1${PROXY_BLOCK}`,
)

if (patched === content) {
  console.error('Could not find insertion point in vite.config.ts')
  process.exit(1)
}

writeFileSync(VITE_CONFIG, patched, 'utf-8')
console.log('vite.config.ts — PostgREST proxy added.')
