/**
 * ICD Test Runner — CRUD: Dashboard Package (v0.31.1)
 * Tests the dashboard .pkg lifecycle: install → surface accessible →
 * settings → export/import round-trip.
 * Uses T.crud.buildTestZip() from _helpers.js.
 */
(function () {
  'use strict';
  var T = window.ICD;
  if (!T) return;
  if (!T.crud) T.crud = {};

  var buildTestZip = T.crud.buildTestZip;

  T.crud.dashboardPackage = async function (testTag) {

    if (T.user.role !== 'admin') return;

    // ── dashpkg: Dashboard package install + lifecycle ──

    var dashPkgId = null;

    await T.test('crud', 'dashboardPackage', 'dashpkg: POST /admin/packages/install (dashboard .pkg)', async function () {
      var manifest = JSON.stringify({
        id: 'dashboard',
        title: 'Dashboard',
        type: 'full',
        version: '0.31.1',
        tier: 'browser',
        author: 'Switchboard Core',
        description: 'Project dashboard exercising all SDK primitives',
        route: '/s/dashboard',
        permissions: [],
        settings: [
          { key: 'refresh_interval', label: 'Auto-Refresh (seconds)', type: 'number', 'default': 0 }
        ]
      });
      var zipBlob = buildTestZip({
        'manifest.json': manifest,
        'js/main.js': '// dashboard package entry point\nconsole.log("[DashboardPkg] loaded");',
        'css/main.css': '.surface-dashboard { display: flex; }'
      });

      var d = await T.apiUpload('/admin/packages/install', zipBlob, 'dashboard.pkg');
      T.assert(d.id === 'dashboard', 'package id should be "dashboard", got: ' + d.id);
      dashPkgId = d.id;

      T.registerCleanup(async function () {
        if (dashPkgId) {
          var token = await T.getAuthToken();
          return T.authFetch(token, 'DELETE', '/admin/packages/' + dashPkgId);
        }
      });
    });

    if (!dashPkgId) return;

    await T.test('crud', 'dashboardPackage', 'dashpkg: GET /admin/packages/:id (verify type full)', async function () {
      var d = await T.apiGet('/admin/packages/' + dashPkgId);
      T.assertShape(d, T.S.extension, 'dashboard package');
      T.assert(d.type === 'full', 'type should be "full", got: ' + d.type);
      T.assert(d.tier === 'browser', 'tier should be "browser", got: ' + d.tier);
      T.assert(d.source === 'extension', 'source should be "extension", got: ' + d.source);
      T.assert(d.enabled === true, 'newly installed package should be enabled');
      T.assert(d.version === '0.31.1', 'version mismatch');
    });

    await T.test('crud', 'dashboardPackage', 'dashpkg: GET /admin/surfaces (dashboard in list)', async function () {
      var d = await T.apiGet('/admin/surfaces');
      T.assertHasKey(d, 'data', '/admin/surfaces');
      var found = d.data.some(function (s) { return s.id === 'dashboard'; });
      T.assert(found, 'dashboard package should appear in surfaces list');
    });

    // ── Settings ──

    await T.test('crud', 'dashboardPackage', 'dashpkg: GET /admin/packages/:id/settings', async function () {
      var d = await T.apiGet('/admin/packages/' + dashPkgId + '/settings');
      T.assert(typeof d === 'object', 'settings should be an object');
    });

    await T.test('crud', 'dashboardPackage', 'dashpkg: PUT /admin/packages/:id/settings', async function () {
      var settings = { refresh_interval: 30 };
      var d = await T.apiPut('/admin/packages/' + dashPkgId + '/settings', settings);
      T.assert(d._status === 200 || d._status === 204 || !d._status, 'settings PUT should succeed');

      // Verify persistence
      var check = await T.apiGet('/admin/packages/' + dashPkgId + '/settings');
      var vals = check.values || {};
      T.assert(vals.refresh_interval === 30, 'refresh_interval should persist as 30');
    });

    // ── Export/Import Round-Trip ──

    var exportBlob = null;

    await T.test('crud', 'dashboardPackage', 'dashpkg: GET /admin/packages/:id/export', async function () {
      var token = await T.getAuthToken();
      var resp = await fetch(T.base + '/api/v1/admin/packages/' + dashPkgId + '/export', {
        headers: { 'Authorization': 'Bearer ' + token }
      });
      T.assert(resp.ok, 'export should return 200, got: ' + resp.status);
      exportBlob = await resp.blob();
      T.assert(exportBlob.size > 0, 'export blob should not be empty');
    });

    if (exportBlob) {
      await T.test('crud', 'dashboardPackage', 'dashpkg: DELETE + re-import round-trip', async function () {
        var token = await T.getAuthToken();
        var delResp = await T.authFetch(token, 'DELETE', '/admin/packages/' + dashPkgId);
        T.assert(!delResp._status || delResp._status < 300, 'delete should succeed');

        var d = await T.apiUpload('/admin/packages/install', exportBlob, 'dashboard.pkg');
        T.assert(d.id === 'dashboard', 'reimported package id should be "dashboard"');

        var check = await T.apiGet('/admin/packages/' + dashPkgId);
        T.assert(check.id === 'dashboard', 'reimported dashboard should be readable');
        T.assert(check.type === 'full', 'reimported type should be "full"');
      });
    }
  };
})();
