import http from'node:http';import{setTimeout as wait}from'node:timers/promises';
export function createServer(){let counter=0,next=1;const orders=new Map();return http.createServer(async(req,res)=>{const u=new URL(req.url,'http://localhost');function send(code,data){res.writeHead(code,{'Content-Type':'application/json','Cache-Control':'no-store'});res.end(JSON.stringify(data));}if(req.url.length>2048)return send(414,{error:'URL too long'});if(req.method==='GET'&&u.pathname==='/health')return send(200,{ok:true,service:'local-k6-training'});if(req.method==='GET'&&u.pathname==='/report'){const p=u.searchParams.get('profile')||'fast';if(!['fast','slow','error'].includes(p))return send(422,{error:'profile'});await wait(p==='slow'?240:20);const fail=p==='error'&&++counter%3===0;return send(fail?503:200,fail?{error:'intentional training failure'}:{ok:true,rows:24,total_minor:128000});}if(req.method==='POST'&&u.pathname==='/login')return send(200,{token:'training-only-token',warning:'not real authentication'});if(u.pathname.startsWith('/orders')){if(req.headers.authorization!=='Bearer training-only-token')return send(401,{error:'token required'});if(req.method==='POST'&&u.pathname==='/orders'){let body='';for await(const chunk of req){body+=chunk;if(Buffer.byteLength(body)>2048)return send(413,{error:'body too large'});}let input;try{input=JSON.parse(body);}catch{return send(400,{error:'json'});}if(!input||Array.isArray(input)||typeof input!=='object'||typeof input.title!=='string'||input.title.length>80||!input.title.trim())return send(422,{error:'title'});if(orders.size>=200)orders.delete(orders.keys().next().value);const order={id:next++,title:input.title};orders.set(order.id,order);return send(201,order);}if(req.method==='GET'){const order=orders.get(Number(u.pathname.split('/')[2]));return send(order?200:404,order||{error:'not found'});}}send(404,{error:'not found'});});}
if(import.meta.url===new URL(process.argv[1],'file:').href||process.argv[1]?.replaceAll('\\','/').endsWith('/src/server.mjs')){const server=createServer();server.requestTimeout=5000;server.headersTimeout=6000;server.listen(Number(process.env.PORT||8320),process.env.HOST||'127.0.0.1',()=>console.log('local training API ready'));for(const sig of['SIGINT','SIGTERM'])process.on(sig,()=>server.close(()=>process.exit(0)));}
