// Seed a support queue + one available agent. Run against a running service.
import 'dotenv/config';
import jwt from 'jsonwebtoken';

const SERVICE = process.env.SMOKE_URL ?? 'http://localhost:3200';
const APP_ID = 'portal-demo';
const SECRET = JSON.parse(process.env.APP_SECRETS ?? '{"portal-demo":"dev-secret"}')[APP_ID];
const sign = (u) => jwt.sign({ sub: u, name: u, appId: APP_ID, orgId: `org_${APP_ID}` }, SECRET, { algorithm: 'HS256', expiresIn: '2h' });

async function api(path, method, token, 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}`);
  return r.json();
}

const agentToken = sign(process.env.AGENT_ID ?? 'agent1');
const queue = await api('/v1/support/queues', 'POST', agentToken, { name: 'Support' });
await api(`/v1/support/queues/${queue.id}/members`, 'POST', agentToken);
await api('/v1/support/members/me/availability', 'PATCH', agentToken, { state: 'AVAILABLE' });
console.log(`seeded queue ${queue.id}; agent AVAILABLE`);
process.exit(0);
