// smoke: permission read endpoints (Bearer, no RBAC required)
//
// Covers:
//   GET /api/v1/permissions/catalog          (?tree=true and flat)
//   GET /api/v1/permissions/me               (regular user → empty roles ok)
//   GET /api/v1/permissions/me?include_tree=true
import { get, checkEnvelope } from '../lib/http.js';
import { registerAndConfirm } from '../lib/auth.js';

export const options = {
  vus: 1,
  iterations: 1,
  thresholds: { checks: ['rate==1.0'] },
};

export default function () {
  const { tokens } = registerAndConfirm();
  const bearer = { Authorization: `Bearer ${tokens.access_token}` };

  // GET /catalog (flat). When the catalog is empty (no perms seeded into
  // gateway_k6) the Go struct uses `omitempty`, so both list and tree are
  // legitimately stripped from the response; the envelope success is enough
  // to prove the endpoint and auth chain work. When perms ARE seeded
  // (after k6-seed-admin), .list is a non-empty array.
  const flat = checkEnvelope(get('/api/v1/permissions/catalog', bearer), 'GET /permissions/catalog').data;
  if (flat && flat.list !== undefined && !Array.isArray(flat.list)) {
    throw new Error(`catalog: .list is not an array: ${JSON.stringify(flat)}`);
  }

  // GET /catalog?tree=true (same envelope-only assertion).
  const tree = checkEnvelope(get('/api/v1/permissions/catalog?tree=true', bearer), 'GET /permissions/catalog?tree=true').data;
  if (tree && tree.tree !== undefined && !Array.isArray(tree.tree)) {
    throw new Error(`catalog tree: .tree is not an array: ${JSON.stringify(tree)}`);
  }

  // GET /me
  const me = checkEnvelope(get('/api/v1/permissions/me', bearer), 'GET /permissions/me').data;
  if (me.uid !== tokens.uid) throw new Error('me.uid mismatch');
  if (!Array.isArray(me.roles)) throw new Error('me.roles is not array');

  // GET /me?include_tree=true
  checkEnvelope(get('/api/v1/permissions/me?include_tree=true', bearer), 'GET /permissions/me?include_tree=true');
}
