import http from 'node:http';
import pino from 'pino';
import {randomUUID} from 'node:crypto';
import {performance} from 'node:perf_hooks';
import {pathToFileURL} from 'node:url';
export function createDemoServer(destination){
 const logger=pino({level:process.env.LOG_LEVEL||'info',redact:{paths:['req.headers.authorization','req.headers.cookie'],censor:'[HIDDEN]'}},destination);
 return http.createServer((req,res)=>{
  const requestId=randomUUID();const started=performance.now();
  // Never let client-provided top-level keys override logger fields.
  let path;
  try { path=new URL(req.url,'http://localhost').pathname; }
  catch { path=null; }
  const known=['/health','/orders','/fail'].includes(path);
  const log=logger.child({requestId,route:known?path:'unmatched'});res.setHeader('x-request-id',requestId);
  res.on('finish',()=>log.info({statusCode:res.statusCode,durationMs:Math.round((performance.now()-started)*100)/100},'Запрос завершён'));
  res.on('close',()=>{if(!res.writableFinished)log.warn('Клиент закрыл соединение');});
  res.setHeader('content-type','application/json; charset=utf-8');
  if(path===null){log.warn({code:'INVALID_REQUEST_TARGET'},'Некорректный адрес запроса');res.writeHead(400).end(JSON.stringify({error:'invalid_request_target',requestId}));return;}
  if(req.method!=='GET'){res.writeHead(405,{Allow:'GET'}).end(JSON.stringify({error:'method_not_allowed'}));return;}
  if(path==='/health'){res.end(JSON.stringify({ok:true}));return;}
  if(path==='/orders'){log.info({count:2},'Учебные заказы прочитаны');res.end(JSON.stringify({orders:[{id:41,status:'new'},{id:42,status:'paid'}]}));return;}
  if(path==='/fail'){const err=new Error('Учебная ошибка склада');log.error({err},'Операция прервана');res.writeHead(503).end(JSON.stringify({error:'demo_unavailable',requestId}));return;}
  res.writeHead(404).end(JSON.stringify({error:'not_found'}));
 });
}
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){
 const server=createDemoServer();server.listen(Number(process.env.PORT||8284),'127.0.0.1');
 for(const signal of ['SIGINT','SIGTERM'])process.once(signal,()=>{server.close(()=>process.exit(0));setTimeout(()=>process.exit(1),5000).unref();});
}
