#!/bin/bash
# Run this from the VPS when you need to manually run migrations
# Usage: bash scripts/migrate.sh

NETWORK=$(docker inspect $(docker ps | grep portfoliodb | awk '{print $1}' | head -1) --format '{{range $k, $v := .NetworkSettings.Networks}}{{$k}}{{end}}')
APP_IMAGE=$(docker images | grep portfolio-web | awk '{print $1}' | head -1)

docker run --rm \
  --network $NETWORK \
  -e DATABASE_URL=postgresql://postgres:TrojanHero1@portfolio-portfoliodb-22lpk0:5432/postgres \
  -e PAYLOAD_SECRET=n8Kj2vR5pL9mQx7tY3wE6bZ1aD4sF0hU9cV2xB5nM8pL1q \
  $APP_IMAGE \
  sh -c "cat > /tmp/migrate.ts << 'EOF'
import { drizzle } from 'drizzle-orm/node-postgres'
import pg from 'pg'

async function main() {
  const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
  const migrations = await import('/app/src/migrations/index.ts')
  console.log('running migrations...')
  for (const [name, migration] of Object.entries(migrations)) {
    if (typeof migration === 'function') {
      console.log('running:', name)
      await migration({ db: drizzle(pool) })
    }
  }
  console.log('done')
  await pool.end()
}

main().catch(console.error)
EOF
node_modules/.bin/tsx /tmp/migrate.ts"