// P6 route smoke: preview-first, deny-by-default, approve→sandbox, AUTOMATIC auto-forward.
// Requires service running (relay timer on) with IIOS_DEV_TOKENS not needed here —
// we mint our own session token + sign webhooks directly. No real network is contacted.
import 'dotenv/config';
import crypto from 'node:crypto';
import jwt from 'jsonwebtoken';

const SERVICE = process.env.SMOKE_URL ?? 'http://localhost:3200';
const APP_ID = 'portal-demo';
const APP_SECRET = JSON.parse(process.env.APP_SECRETS ?? '{"portal-demo":"dev-secret"}')[APP_ID];
const ADAPTER_SECRET = (() => {
  try { return JSON.parse(process.env.ADAPTER_SECRETS ?? '{}').WEBHOOK ?? 'dev-adapter-secret'; } catch { return 'dev-adapter-secret'; }
})();

const token = jwt.sign({ sub: 'route-admin', appId: APP_ID, orgId: `org_${APP_ID}` }, APP_SECRET, { algorithm: 'HS256', expiresIn: '1h' });
const sign = (body) => 'sha256=' + crypto.createHmac('sha256', ADAPTER_SECRET).update(body).digest('hex');
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const assert = (c, m) => { if (!c) { console.error('✗', m); process.exit(1); } console.log('✓', m); };

async function req(path, method = 'GET', body) {
  const r = await fetch(`${SERVICE}${path}`, {
    method,
    headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
    body: body ? JSON.stringify(body) : undefined,
  });
  if (!r.ok) throw new Error(`${method} ${path} ${r.status}: ${await r.text()}`);
  return r.json();
}
async function pollUntil(fn, ms = 8000) {
  const end = Date.now() + ms;
  while (Date.now() < end) { const v = await fn(); if (v) return v; await sleep(300); }
  return null;
}
const outboundCount = async () => (await req('/v1/adapters/outbound')).length;

async function ingest(text) {
  const payload = { eventId: `route-sm-${crypto.randomUUID()}`, from: 'sim@parent', text, threadRef: `sm-${Date.now()}` };
  const body = JSON.stringify(payload);
  const wh = await fetch(`${SERVICE}/v1/adapters/WEBHOOK/webhook`, {
    method: 'POST',
    headers: { 'content-type': 'application/json', 'x-iios-signature': sign(body) },
    body,
  });
  if (wh.status !== 202) throw new Error(`webhook ${wh.status}`);
  const e = await pollUntil(async () => {
    const list = await req('/v1/adapters/inbound');
    const hit = list.find((x) => x.externalEventId === payload.eventId);
    return hit && hit.interactionId ? hit : null;
  });
  if (!e) throw new Error('interaction never normalized');
  return e.interactionId;
}

// ── Phase A: three MANUAL bindings, preview-first ──────────────────────────
const mk = (destinationRef, restrictionProfile) => req('/v1/routes/bindings', 'POST', {
  originChannelType: 'WEBHOOK', destinationChannelType: 'PORTAL', destinationRef,
  restrictionProfile, mode: 'MANUAL', requiresReview: true, enabled: true,
});
const adult = await mk('adults', undefined);
const seniors = await mk('seniors', undefined);
const children = await mk('children', 'CHILD');
assert(adult.id && seniors.id && children.id, 'created 3 bindings (adults / seniors / children[CHILD])');

const base = await outboundCount();
const interactionId = await ingest('There is a party at 9 PM tonight!');
const { decisions } = await req('/v1/routes/simulate', 'POST', { interactionId, originChannelType: 'WEBHOOK' });
const byBinding = Object.fromEntries(decisions.map((d) => [d.routeBindingId, d]));
assert(byBinding[children.id]?.decisionState === 'DENY', 'children (restricted) → DENY (deny-by-default)');
assert(byBinding[adult.id]?.decisionState === 'REVIEW', 'adults → REVIEW');
assert(byBinding[seniors.id]?.decisionState === 'REVIEW', 'seniors → REVIEW');
assert((await outboundCount()) === base, 'simulate sent nothing (0 new outbound commands)');

// ── Phase B: approve a REVIEW decision → forwards to sandbox ────────────────
const approved = await req(`/v1/routes/decisions/${byBinding[seniors.id].id}/approve`, 'POST');
assert(approved.decisionState === 'ALLOW' && approved.executed, 'approved seniors → ALLOW + executed');
assert((await outboundCount()) === base + 1, 'approval produced exactly one sandbox forward');

// ── Phase C: AUTOMATIC safe binding → auto-forward on ingest ────────────────
// originRef 'webhook' = the WEBHOOK adapter's channel id, so the RouteProjector
// (which matches on the interaction's channel ref) picks this binding up.
await req('/v1/routes/bindings', 'POST', {
  originChannelType: 'WEBHOOK', originRef: 'webhook', destinationChannelType: 'PORTAL', destinationRef: 'staff',
  mode: 'AUTOMATIC', requiresReview: false, enabled: true,
});
const base2 = await outboundCount();
await ingest('Team standup notes are posted for everyone.');
const grew = await pollUntil(async () => (await outboundCount()) > base2, 8000);
assert(grew, 'AUTOMATIC safe binding auto-forwarded (sandbox) via RouteProjector');

console.log('\nP6 route smoke: PASS');
process.exit(0);
