import json
import subprocess
from pathlib import Path


OFFLINE_CLOSE = Path(__file__).parents[1] / "frontend" / "offline-issue-close.js"


def run_node(script: str):
    result = subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True)
    return json.loads(result.stdout)


def test_offline_issue_close_waits_for_durable_admission_before_advancing_today():
    script = f"""
const createOfflineIssueClose = require({json.dumps(str(OFFLINE_CLOSE))});
const events=[]; let release;
const gate=new Promise(resolve=>release=resolve);
const close=createOfflineIssueClose({{
  enqueueDurably:async message=>{{events.push('admit');await gate;events.push('durable');return {{item:message,background:true}};}},
  completeToday:item=>{{events.push('complete:' + item.number);return true;}},
}});
const item={{kind:'issue',repository:'stackchain/dashboard',number:27}};
const pending=close(item).then(result=>{{events.push('resolved');return result;}});
Promise.resolve().then(async()=>{{
  const before=events.slice();release();const result=await pending;
  process.stdout.write(JSON.stringify({{before,events,result}}));
}});
"""
    output = run_node(script)

    assert output["before"] == ["admit"]
    assert output["events"] == ["admit", "durable", "complete:27", "resolved"]
    assert output["result"]["advanced"] is True
    assert output["result"]["admission"]["background"] is True
