/**
 * SDK Test Runner — Domain: dependencies (v0.38.2)
 *
 * Tests library package install, dependency creation, uninstall
 * protection, and admin dependency visibility endpoints.
 * Requires admin role.
 */
(function () {
  'use strict';
  var T = window.SDKR;
  if (!T) return;

  // ── Minimal zip builder (same as packages.js) ───────────
  function buildZip(entries) {
    var localHeaders = [];
    var centralHeaders = [];
    var offset = 0;
    entries.forEach(function (entry) {
      var nameBytes = new TextEncoder().encode(entry.name);
      var dataBytes = new TextEncoder().encode(entry.content);
      var local = new Uint8Array(30 + nameBytes.length + dataBytes.length);
      var dv = new DataView(local.buffer);
      dv.setUint32(0, 0x04034b50, true);
      dv.setUint16(4, 20, true);
      dv.setUint16(8, 0, true);
      dv.setUint16(10, 0, true);
      dv.setUint16(12, 0, true);
      dv.setUint32(14, crc32(dataBytes), true);
      dv.setUint32(18, dataBytes.length, true);
      dv.setUint32(22, dataBytes.length, true);
      dv.setUint16(26, nameBytes.length, true);
      dv.setUint16(28, 0, true);
      local.set(nameBytes, 30);
      local.set(dataBytes, 30 + nameBytes.length);
      localHeaders.push(local);
      var central = new Uint8Array(46 + nameBytes.length);
      var cdv = new DataView(central.buffer);
      cdv.setUint32(0, 0x02014b50, true);
      cdv.setUint16(4, 20, true);
      cdv.setUint16(6, 20, true);
      cdv.setUint16(28, nameBytes.length, true);
      cdv.setUint32(16, crc32(dataBytes), true);
      cdv.setUint32(20, dataBytes.length, true);
      cdv.setUint32(24, dataBytes.length, true);
      cdv.setUint32(42, offset, true);
      central.set(nameBytes, 46);
      centralHeaders.push(central);
      offset += local.length;
    });
    var centralSize = centralHeaders.reduce(function (s, c) { return s + c.length; }, 0);
    var eocd = new Uint8Array(22);
    var edv = new DataView(eocd.buffer);
    edv.setUint32(0, 0x06054b50, true);
    edv.setUint16(8, entries.length, true);
    edv.setUint16(10, entries.length, true);
    edv.setUint32(12, centralSize, true);
    edv.setUint32(16, offset, true);
    var result = new Uint8Array(offset + centralSize + 22);
    var pos = 0;
    localHeaders.forEach(function (h) { result.set(h, pos); pos += h.length; });
    centralHeaders.forEach(function (h) { result.set(h, pos); pos += h.length; });
    result.set(eocd, pos);
    return new Blob([result], { type: 'application/zip' });
  }

  var crcTable = null;
  function crc32(bytes) {
    if (!crcTable) {
      crcTable = new Uint32Array(256);
      for (var n = 0; n < 256; n++) {
        var c = n;
        for (var k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
        crcTable[n] = c;
      }
    }
    var crc = 0xFFFFFFFF;
    for (var i = 0; i < bytes.length; i++) crc = crcTable[(crc ^ bytes[i]) & 0xFF] ^ (crc >>> 8);
    return (crc ^ 0xFFFFFFFF) >>> 0;
  }

  function makePkgFile(manifest, extraFiles) {
    var entries = [{ name: 'manifest.json', content: JSON.stringify(manifest) }];
    if (extraFiles) entries = entries.concat(extraFiles);
    var blob = buildZip(entries);
    return new File([blob], manifest.id + '.pkg', { type: 'application/zip' });
  }

  // ── Tests ────────────────────────────────────────────────

  T.registerDomain('dependencies', async function () {

    if (!window.sw || !sw.isAdmin) {
      await T.test('dependencies', 'guard', 'skip — not admin', async function () {
        T.assert(true, 'skipped (user is not admin)');
      });
      return;
    }

    var libId = 'sdk-test-lib-' + Date.now();
    var consumerId = 'sdk-test-consumer-' + Date.now();

    // ── 1. Install library ────────────────────────

    await T.test('dependencies', 'install-library', 'install library package', async function () {
      var manifest = {
        id: libId,
        title: 'SDK Test Library',
        type: 'library',
        tier: 'starlark',
        version: '1.0.0',
        exports: ['get_data', 'transform'],
        permissions: []
      };
      var file = makePkgFile(manifest, [
        { name: 'script.star', content: 'def get_data():\n    return {"ok": True}\n\ndef transform(x):\n    return x\n' }
      ]);
      var r = await sw.api.admin.packages.install(file);
      T.assert(r && r.id === libId, 'library should install');
      T.assert(r.type === 'library', 'type should be library');
    });

    T.cleanup.push(async function () {
      try { await sw.api.admin.packages.del(libId); } catch (_) {}
    });

    // ── 2. Verify library in package list ────────────────

    await T.test('dependencies', 'library-in-list', 'library appears in package list', async function () {
      var r = await sw.api.admin.packages.get(libId);
      T.assert(r && r.type === 'library', 'should be type library');
      T.assert(r.version === '1.0.0', 'version should match');
    });

    // ── 3. Install consumer with dependency ────────────────

    await T.test('dependencies', 'install-consumer', 'install consumer with dependency on library', async function () {
      var manifest = {
        id: consumerId,
        title: 'SDK Test Consumer',
        type: 'extension',
        tier: 'starlark',
        version: '0.1.0',
        tools: [{ name: 'noop', description: 'test', parameters: { type: 'object', properties: {} } }],
        dependencies: {}
      };
      manifest.dependencies[libId] = '>=1.0.0';
      var file = makePkgFile(manifest, [
        { name: 'script.star', content: 'def on_tool_call(call):\n    return {"ok": True}\n' }
      ]);
      var r = await sw.api.admin.packages.install(file);
      T.assert(r && r.id === consumerId, 'consumer should install');
    });

    T.cleanup.push(async function () {
      try { await sw.api.admin.packages.del(consumerId); } catch (_) {}
    });

    // ── 4. Verify dependency records ────────────────

    await T.test('dependencies', 'list-dependencies', 'admin can list consumer dependencies', async function () {
      var r = await sw.api.admin.packages.dependencies(consumerId);
      T.assert(r && r.data, 'should return data');
      T.assert(r.data.length === 1, 'should have 1 dependency');
      T.assert(r.data[0].library_id === libId, 'library_id should match');
      T.assert(r.data[0].version_spec === '>=1.0.0', 'version_spec should match');
    });

    // ── 5. Verify consumer records ────────────────

    await T.test('dependencies', 'list-consumers', 'admin can list library consumers', async function () {
      var r = await sw.api.admin.packages.consumers(libId);
      T.assert(r && r.data, 'should return data');
      T.assert(r.data.length === 1, 'should have 1 consumer');
      T.assert(r.data[0].consumer_id === consumerId, 'consumer_id should match');
    });

    // ── 6. Uninstall protection ────────────────

    await T.test('dependencies', 'uninstall-protection', 'cannot uninstall library with active consumers', async function () {
      try {
        await sw.api.admin.packages.del(libId);
        T.assert(false, 'should have been rejected');
      } catch (e) {
        var msg = (e && e.message) || String(e);
        T.assert(
          msg.indexOf('409') >= 0 || msg.indexOf('active consumers') >= 0 || msg.indexOf('Conflict') >= 0,
          'expected 409 conflict, got: ' + msg
        );
      }
    });

    // ── 7. Uninstall consumer, verify cleanup ────────────────

    await T.test('dependencies', 'uninstall-consumer', 'uninstall consumer cleans up dependencies', async function () {
      await sw.api.admin.packages.del(consumerId);
      consumerId = null; // disable cleanup

      var r = await sw.api.admin.packages.consumers(libId);
      T.assert(r && r.data, 'should return data');
      T.assert(r.data.length === 0, 'library should have 0 consumers after uninstall');
    });

    // ── 8. Library uninstall succeeds ────────────────

    await T.test('dependencies', 'uninstall-library', 'library can be uninstalled after consumers removed', async function () {
      await sw.api.admin.packages.del(libId);
      libId = null; // disable cleanup

      // Verify it's gone
      try {
        await sw.api.admin.packages.get(libId);
        T.assert(false, 'should be deleted');
      } catch (e) {
        T.assert(true, 'library deleted successfully');
      }
    });

  });
})();
