/**
 * ICD Test Runner — Packaging Tier
 *
 * v0.29.0 CS5: Tests the extension permission lifecycle
 * (install with permissions → pending_review → grant → active →
 * revoke → suspended) and extension secrets CRUD.
 *
 * Requires admin token (from fixtures).
 */
(function () {
  'use strict';
  var T = window.ICD;
  if (!T) return;

  T.runPackaging = async function () {
    var extId = 'icd-pkg-' + Date.now();
    var extInstalled = false;

    // ── Install with permissions → pending_review ──

    await T.test('crud', 'packaging', 'POST /admin/extensions (with permissions)', async function () {
      var d = await T.apiPost('/admin/extensions', {
        ext_id: extId,
        name: 'ICD Packaging Test',
        version: '1.0.0',
        tier: 'starlark',
        description: 'Tests permission lifecycle',
        author: 'icd-runner',
        manifest: {
          permissions: ['secrets.read', 'notifications.send'],
          _starlark_script: 'def on_run():\n    return "ok"'
        },
        is_enabled: true,
        is_system: false
      });
      T.assertHasKey(d, 'data', 'install response');
      T.assert(d.data.id === extId, 'id should match ext_id');
      T.assert(d.data.tier === 'starlark', 'tier should be starlark');
      extInstalled = true;
      T.registerCleanup(function () {
        if (extInstalled) return T.safeDelete('/admin/extensions/' + extId);
      });
    });

    if (!extInstalled) return;

    // ── Verify pending_review status ──

    await T.test('crud', 'packaging', 'GET /admin/extensions/:id (status = pending_review)', async function () {
      var d = await T.apiGet('/admin/extensions');
      T.assertHasKey(d, 'data', 'admin list');
      var pkg = d.data.find(function (e) { return e.id === extId; });
      T.assert(pkg, 'installed package should be in admin list');
      T.assert(pkg.status === 'pending_review', 'status should be pending_review, got: ' + pkg.status);
    });

    // ── List declared permissions ──

    await T.test('crud', 'packaging', 'GET /admin/extensions/:id/permissions (declared)', async function () {
      var d = await T.apiGet('/admin/extensions/' + extId + '/permissions');
      T.assertHasKey(d, 'data', 'permissions response');
      T.assert(Array.isArray(d.data), 'permissions should be array');
      T.assert(d.data.length === 2, 'should have 2 declared permissions, got: ' + d.data.length);

      var perms = d.data.map(function (p) { return p.permission; }).sort();
      T.assert(perms[0] === 'notifications.send', 'first perm should be notifications.send');
      T.assert(perms[1] === 'secrets.read', 'second perm should be secrets.read');

      var allUngrated = d.data.every(function (p) { return p.granted === false; });
      T.assert(allUngrated, 'all permissions should be ungranted initially');
    });

    // ── Review package ──

    await T.test('crud', 'packaging', 'GET /admin/extensions/:id/review', async function () {
      var d = await T.apiGet('/admin/extensions/' + extId + '/review');
      T.assertHasKey(d, 'package', 'review response package');
      T.assertHasKey(d, 'permissions', 'review response permissions');
      T.assert(d.package.id === extId, 'review package id should match');
      T.assert(Array.isArray(d.permissions), 'review permissions should be array');
      T.assert(d.permissions.length === 2, 'review should show 2 permissions');
    });

    // ── Grant single permission ──

    await T.test('crud', 'packaging', 'POST .../permissions/secrets.read/grant', async function () {
      var d = await T.apiPost('/admin/extensions/' + extId + '/permissions/secrets.read/grant', {});
      T.assert(d.status === 'granted', 'should return granted status');
      T.assert(d.permission === 'secrets.read', 'should echo permission');
    });

    // ── Still pending_review (not all granted) ──

    await T.test('crud', 'packaging', 'status still pending_review (1 of 2 granted)', async function () {
      var d = await T.apiGet('/admin/extensions');
      var pkg = d.data.find(function (e) { return e.id === extId; });
      T.assert(pkg.status === 'pending_review', 'should still be pending_review, got: ' + pkg.status);
    });

    // ── Grant all remaining ──

    await T.test('crud', 'packaging', 'POST .../permissions/grant-all', async function () {
      var d = await T.apiPost('/admin/extensions/' + extId + '/permissions/grant-all', {});
      T.assert(d.status === 'granted_all', 'should return granted_all status');
    });

    // ── Verify active status ──

    await T.test('crud', 'packaging', 'status → active (all permissions granted)', async function () {
      var d = await T.apiGet('/admin/extensions');
      var pkg = d.data.find(function (e) { return e.id === extId; });
      T.assert(pkg.status === 'active', 'should be active after grant-all, got: ' + pkg.status);
    });

    // ── Verify all granted ──

    await T.test('crud', 'packaging', 'GET .../permissions (all granted)', async function () {
      var d = await T.apiGet('/admin/extensions/' + extId + '/permissions');
      var allGranted = d.data.every(function (p) { return p.granted === true; });
      T.assert(allGranted, 'all permissions should be granted');
      var hasGrantedBy = d.data.every(function (p) { return p.granted_by !== null; });
      T.assert(hasGrantedBy, 'all permissions should have granted_by');
    });

    // ── Secrets CRUD ──

    await T.test('crud', 'packaging', 'PUT /admin/extensions/:id/secrets (set)', async function () {
      var d = await T.apiPut('/admin/extensions/' + extId + '/secrets', {
        secrets: { api_key: 'sk-test-123', webhook_token: 'tok-abc' }
      });
      T.assert(d.status === 'saved', 'should return saved status');
      T.assert(d.key_count === 2, 'should report 2 keys');
    });

    await T.test('crud', 'packaging', 'GET /admin/extensions/:id/secrets (keys only)', async function () {
      var d = await T.apiGet('/admin/extensions/' + extId + '/secrets');
      T.assertHasKey(d, 'data', 'secrets response');
      T.assert(d.data.package_id === extId, 'package_id should match');
      T.assert(Array.isArray(d.data.keys), 'keys should be array');
      T.assert(d.data.keys.length === 2, 'should have 2 keys');
      // Values should NOT be returned
      T.assert(!d.data.api_key, 'raw values should not be exposed');
    });

    await T.test('crud', 'packaging', 'DELETE /admin/extensions/:id/secrets', async function () {
      var d = await T.apiDelete('/admin/extensions/' + extId + '/secrets');
      T.assert(d.status === 'deleted', 'should return deleted status');
    });

    await T.test('crud', 'packaging', 'GET .../secrets (empty after delete)', async function () {
      var d = await T.apiGet('/admin/extensions/' + extId + '/secrets');
      T.assert(d.data.keys.length === 0, 'keys should be empty after delete');
    });

    // ── Revoke → suspended ──

    await T.test('crud', 'packaging', 'POST .../permissions/secrets.read/revoke', async function () {
      var d = await T.apiPost('/admin/extensions/' + extId + '/permissions/secrets.read/revoke', {});
      T.assert(d.status === 'revoked', 'should return revoked status');
    });

    await T.test('crud', 'packaging', 'status → suspended (permission revoked)', async function () {
      var d = await T.apiGet('/admin/extensions');
      var pkg = d.data.find(function (e) { return e.id === extId; });
      T.assert(pkg.status === 'suspended', 'should be suspended after revoke, got: ' + pkg.status);
    });

    // ── Invalid permission ──

    await T.test('crud', 'packaging', 'POST .../permissions/bogus/grant (400)', async function () {
      var d = await T.authFetch(API.accessToken, 'POST', '/admin/extensions/' + extId + '/permissions/bogus/grant', {});
      T.assertStatus(d, 400, 'invalid permission should 400');
    });

    // ── Cleanup (DELETE handled by registerCleanup) ──

    await T.test('crud', 'packaging', 'DELETE /admin/extensions/:id (cleanup)', async function () {
      var d = await T.apiDelete('/admin/extensions/' + extId);
      extInstalled = false;
    });
  };
})();
