import http from'k6/http';import{check,sleep}from'k6';
const CASE=__ENV.CASE||'smoke',BASE=__ENV.BASE_URL||'http://127.0.0.1:8320';
if(!/^http:\/\/(127\.0\.0\.1|localhost|api):8320$/.test(BASE))throw new Error('This teaching script targets only its own local API at port8320. Adapt intentionally for your own authorised environment.');
const cases={smoke:{executor:'shared-iterations',vus:1,iterations:3,maxDuration:'10s'},checks:{executor:'shared-iterations',vus:1,iterations:3,maxDuration:'10s'},budget:{executor:'constant-vus',vus:2,duration:'4s'},ramp:{executor:'ramping-vus',startVUs:1,stages:[{duration:'2s',target:3},{duration:'3s',target:3},{duration:'2s',target:0}]},vus:{executor:'constant-vus',vus:2,duration:'4s'},arrival:{executor:'constant-arrival-rate',rate:8,timeUnit:'1s',duration:'4s',preAllocatedVUs:2,maxVUs:4},tags:{executor:'shared-iterations',vus:1,iterations:5,maxDuration:'10s'},flow:{executor:'shared-iterations',vus:1,iterations:4,maxDuration:'10s'}};
if(!cases[CASE])throw new Error('Unknown CASE');
const thresholds=CASE==='checks'?{}:{checks:['rate==1'],http_req_failed:['rate<0.01'],http_req_duration:['p(95)<150']};
if(CASE==='tags'){thresholds['http_req_duration{route:health}']=['p(95)<100'];thresholds['http_req_duration{route:report}']=['p(95)<100'];}
export const options={scenarios:{main:{...cases[CASE],gracefulStop:'2s'}},thresholds,summaryTrendStats:['avg','min','med','max','p(90)','p(95)','p(99)'],discardResponseBodies:false};
export default function(){
if(CASE==='flow'){const login=http.post(BASE+'/login',null,{tags:{route:'login'}});check(login,{'login200':r=>r.status===200});const token=login.json('token');const opts={headers:{'Content-Type':'application/json',Authorization:'Bearer '+token},tags:{route:'orders'}};const created=http.post(BASE+'/orders',JSON.stringify({title:'Учебная заявка'}),opts);check(created,{'created201':r=>r.status===201});const got=http.get(BASE+'/orders/'+created.json('id'),opts);check(got,{'order available':r=>r.status===200&&r.json('title')==='Учебная заявка'});return;}
if(CASE==='tags'){const a=http.get(BASE+'/health',{tags:{route:'health'}});check(a,{'health200':r=>r.status===200});const b=http.get(BASE+'/report?profile=slow',{tags:{route:'report'}});check(b,{'report200':r=>r.status===200});return;}
const endpoint=CASE==='checks'?'/health':'/report?profile='+(CASE==='budget'?'slow':'fast');const r=http.get(BASE+endpoint,{tags:{route:CASE==='checks'?'health':'report'}});check(r,{'status200':x=>x.status===200,'body contract':x=>CASE==='checks'?x.json('missing')===true:x.json('ok')===true});if(CASE==='budget'){const e=http.get(BASE+'/report?profile=error',{tags:{route:'report-error'}});check(e,{'error profile returns200':x=>x.status===200});}if(CASE!=='arrival')sleep(0.1);
}
export function handleSummary(data){return{[__ENV.SUMMARY||'artifacts/summary.json']:JSON.stringify(data,null,2),stdout:'Saved real k6 summary for '+CASE+'\n'};}
