// P9 slice-9 retention smoke: an aged interaction's snapshot passes its delete window
// and the sweep redacts the content in place (never a hard delete), visible as a
// REDACTED snapshot on /metrics. Requires the service running with IIOS_DEV_TOKENS=1
// and IIOS_RETENTION_DELETE_DAYS=0 IIOS_RETENTION_ARCHIVE_DAYS=0 (new content due at once;
// scheduled interval left OFF so only the explicit dev sweep runs).
import 'dotenv/config';

const SERVICE = process.env.SMOKE_URL ?? 'http://localhost:3200';
const APP_ID = 'portal-demo';
const assert = (c, m) => { if (!c) { console.error('✗', m); process.exit(1); } console.log('✓', m); };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function devToken(userId, orgId) {
  const r = await fetch(`${SERVICE}/v1/dev/token`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ appId: APP_ID, userId, name: userId, orgId }),
  });
  if (!r.ok) throw new Error(`devToken ${r.status} (service with IIOS_DEV_TOKENS=1?)`);
  return (await r.json()).token;
}
async function api(token, 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();
}
const redactedCount = (m) => m.retention?.byStatus?.REDACTED ?? 0;

const token = await devToken('ret-a', 'org_ret_A');

const base = redactedCount(await api(token, '/metrics'));
console.log(`baseline REDACTED snapshots = ${base}`);

// Inject content and give the relay a moment to normalize it into an interaction.
await api(token, '/v1/dev/webhook/WEBHOOK', 'POST', { text: 'retention smoke content' });
await sleep(2000);

// Sweep: 0-day windows make every interaction's snapshot immediately due → redacted.
const swept = await api(token, '/v1/dev/retention/sweep', 'POST');
assert(swept.redacted >= 1, `sweep redacted the aged interaction(s) (redacted=${swept.redacted})`);

const after = await api(token, '/metrics');
assert(redactedCount(after) > base, `/metrics shows more REDACTED snapshots (${base} → ${redactedCount(after)})`);
assert((after.retention?.total ?? 0) >= 1, 'retention.total reflects captured snapshots');

console.log('\nP9 retention smoke: PASS');
process.exit(0);
