/**
 * ICD Test Runner — CRUD: Models
 * Model preference lifecycle — hide/unhide, bulk, validation.
 */
(function () {
  'use strict';
  var T = window.ICD;
  if (!T) return;
  if (!T.crud) T.crud = {};

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

    // ── Model Preferences CRUD ──
    // Depends on provider setup from smoke tier — needs at least one model in /models/enabled

    await T.test('crud', 'models', 'GET /models/preferences (initially empty for test user)', async function () {
      var d = await T.apiGet('/models/preferences');
      T.assertHasKey(d, 'data', '/models/preferences');
      T.assert(Array.isArray(d.data), 'data should be array');
    });

    // Find a model to use for preference tests
    var prefModelId = null;
    var prefConfigId = null;
    await T.test('crud', 'models', 'GET /models/enabled (pick model for pref test)', async function () {
      var d = await T.apiGet('/models/enabled');
      var models = d.data || [];
      var catalog = models.filter(function (m) { return !m.is_persona && m.provider_config_id; });
      if (catalog.length === 0) return;  // no catalog models yet — skip pref write tests
      prefModelId = catalog[0].model_id;
      prefConfigId = catalog[0].provider_config_id;
    });

    if (prefModelId && prefConfigId) {
      await T.test('crud', 'models', 'PUT /models/preferences (hide model)', async function () {
        var d = await T.apiPut('/models/preferences', {
          model_id: prefModelId,
          provider_config_id: prefConfigId,
          hidden: true
        });
        T.assert(d.message === 'preference updated', 'expected success message');
      });

      await T.test('crud', 'models', 'GET /models/preferences (verify hidden)', async function () {
        var d = await T.apiGet('/models/preferences');
        var prefs = d.data || [];
        var found = prefs.find(function (p) {
          return p.model_id === prefModelId && p.provider_config_id === prefConfigId;
        });
        T.assert(found, 'preference entry should exist after PUT');
        T.assert(found.hidden === true, 'hidden should be true');
        T.assertShape(found, T.S.modelPreference, 'preference');
      });

      await T.test('crud', 'models', 'GET /models/enabled (hidden flag propagated)', async function () {
        var d = await T.apiGet('/models/enabled');
        var models = d.data || [];
        var found = models.find(function (m) {
          return m.model_id === prefModelId && m.provider_config_id === prefConfigId;
        });
        if (found) {
          T.assert(found.hidden === true, 'model should have hidden=true in /models/enabled');
        }
      });

      await T.test('crud', 'models', 'PUT /models/preferences (unhide — upsert)', async function () {
        var d = await T.apiPut('/models/preferences', {
          model_id: prefModelId,
          provider_config_id: prefConfigId,
          hidden: false
        });
        T.assert(d.message === 'preference updated', 'expected success message');
      });

      await T.test('crud', 'models', 'GET /models/preferences (verify unhidden, no dup)', async function () {
        var d = await T.apiGet('/models/preferences');
        var prefs = d.data || [];
        var matches = prefs.filter(function (p) {
          return p.model_id === prefModelId && p.provider_config_id === prefConfigId;
        });
        T.assert(matches.length === 1, 'upsert should not duplicate: got ' + matches.length);
        T.assert(matches[0].hidden === false, 'hidden should be false after unhide');
      });

      await T.test('crud', 'models', 'PUT /models/preferences (missing provider_config_id → 400)', async function () {
        var token = await T.getAuthToken();
        var d = await T.authFetch(token, 'PUT', '/models/preferences', { model_id: prefModelId, hidden: true });
        T.assertStatus(d, 400, 'missing provider_config_id');
      });

      await T.test('crud', 'models', 'PUT /models/preferences (missing model_id → 400)', async function () {
        var token = await T.getAuthToken();
        var d = await T.authFetch(token, 'PUT', '/models/preferences', { provider_config_id: prefConfigId, hidden: true });
        T.assertStatus(d, 400, 'missing model_id');
      });

      await T.test('crud', 'models', 'POST /models/preferences/bulk (hide)', async function () {
        var d = await T.apiPost('/models/preferences/bulk', {
          entries: [{ model_id: prefModelId, provider_config_id: prefConfigId }],
          hidden: true
        });
        T.assert(d.message === 'preferences updated', 'expected bulk success message');
        T.assert(d.count === 1, 'count should be 1');
      });

      await T.test('crud', 'models', 'POST /models/preferences/bulk (unhide cleanup)', async function () {
        var d = await T.apiPost('/models/preferences/bulk', {
          entries: [{ model_id: prefModelId, provider_config_id: prefConfigId }],
          hidden: false
        });
        T.assert(d.message === 'preferences updated', 'expected bulk success message');
      });
    }

  };
})();
