// A real loopback HTTP switch backed by a fresh embedded PostgreSQL database.
import http from 'node:http';
import {PGlite} from '@electric-sql/pglite';
import assert from 'node:assert/strict';
const db=new PGlite();let version=1;const checks=[];
await db.exec("CREATE TABLE profiles(id int PRIMARY KEY,full_name text NOT NULL);INSERT INTO profiles VALUES(1,'Mira Chen');");
const server=http.createServer(async(req,res)=>{if(req.url!=='/profile'){res.writeHead(404).end();return;}try{const r=await db.query(version===1?'SELECT full_name AS name FROM profiles':'SELECT display_name AS name FROM profiles');res.writeHead(200,{'Content-Type':'application/json'}).end(JSON.stringify(r.rows));}catch(e){res.writeHead(500).end(e.message);}});
await new Promise(r=>server.listen(0,'127.0.0.1',r));const url=`http://127.0.0.1:${server.address().port}/profile`;
async function probe(label){const response=await fetch(url);assert.equal(response.status,200);checks.push({label,status:response.status,body:await response.json()});}
try{
 await probe('v1 before migration');await db.exec('ALTER TABLE profiles ADD COLUMN display_name text');await db.exec('UPDATE profiles SET display_name=full_name');
 await probe('v1 after expand');version=2;await probe('v2 canary');
 // An injected readiness failure causes an application rollback. Keep expanded schema.
 const canaryReady=false;if(!canaryReady)version=1;await probe('v1 after rollback');
 console.log(JSON.stringify({checks,schemaKept:true,cloudResourcesCreated:0},null,2));
}finally{await new Promise(r=>server.close(r));await db.close();}
