// scripts/switch-db.js
const fs = require('fs')
const path = require('path')

const envPath = path.join(__dirname, '..', '.env')
const schemaPath = path.join(__dirname, '..', 'prisma', 'schema.prisma')

const target = process.argv[2]
if (!['sqlite', 'postgresql'].includes(target)) {
  console.error("Usage: node scripts/switch-db.js [sqlite|postgresql]")
  process.exit(1)
}

// 1. Update schema.prisma
let schemaContent = fs.readFileSync(schemaPath, 'utf8')
// Find the datasource db block and replace the provider
schemaContent = schemaContent.replace(
  /datasource db \{\s*provider\s*=\s*"[^"]+"/g,
  `datasource db {\n  provider = "${target}"`
)
fs.writeFileSync(schemaPath, schemaContent)

// 2. Update .env
let envContent = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf8') : ''
const sqliteUrl = 'file:./dev.db'
const pgUrl = 'postgresql://postgres:postgres@localhost:5432/keep_notes?schema=public'

// Update or append DATABASE_URL
if (target === 'sqlite') {
  if (envContent.match(/^DATABASE_URL=.*$/m)) {
    envContent = envContent.replace(/^DATABASE_URL=.*$/m, `DATABASE_URL="${sqliteUrl}"`)
  } else {
    envContent += `\nDATABASE_URL="${sqliteUrl}"`
  }
} else {
  if (envContent.match(/^DATABASE_URL=.*$/m)) {
    envContent = envContent.replace(/^DATABASE_URL=.*$/m, `DATABASE_URL="${pgUrl}"`)
  } else {
    envContent += `\nDATABASE_URL="${pgUrl}"`
  }
}

fs.writeFileSync(envPath, envContent)

console.log(`✅ Successfully switched database provider to ${target}`)
console.log('You should now run:')
console.log('  npx prisma generate')
console.log('  npx prisma db push')
