/**
 * ICD Test Runner — CRUD: Notes
 * Note lifecycle — create, read, update, search, backlinks, delete.
 */
(function () {
  'use strict';
  var T = window.ICD;
  if (!T) return;
  if (!T.crud) T.crud = {};

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

    // ── Notes CRUD ──
    var noteId = null;
    await T.test('crud', 'notes', 'POST /notes (create)', async function () {
      var d = await T.apiPost('/notes', {
        title: testTag + '-note',
        content: '# ICD Test Note\n\nTest content with [[wikilink]].',
        folder: 'icd-test'
      });
      T.assertShape(d, T.S.note, 'note');
      noteId = d.id;
      T.registerCleanup(function () { if (noteId) return T.safeDelete('/notes/' + noteId); });
    });

    if (noteId) {
      await T.test('crud', 'notes', 'GET /notes/:id (read)', async function () {
        var d = await T.apiGet('/notes/' + noteId);
        T.assertShape(d, T.S.note, 'note');
        T.assert(d.id === noteId, 'id mismatch');
        T.assert(d.title.indexOf(testTag) !== -1, 'title mismatch');
      });

      await T.test('crud', 'notes', 'PUT /notes/:id (update)', async function () {
        var d = await T.apiPut('/notes/' + noteId, {
          title: testTag + '-note-updated',
          content: '# Updated\n\nNew content.'
        });
        T.assert(d.title === testTag + '-note-updated' || (d.id && d.id === noteId), 'update response');
      });

      await T.test('crud', 'notes', 'GET /notes/search', async function () {
        var d = await T.apiGet('/notes/search?q=' + encodeURIComponent(testTag));
        T.assertHasKey(d, 'data', '/notes/search');
      });

      await T.test('crud', 'notes', 'GET /notes/search-titles', async function () {
        var d = await T.apiGet('/notes/search-titles?q=' + encodeURIComponent(testTag));
        T.assertHasKey(d, 'data', '/notes/search-titles');
      });

      await T.test('crud', 'notes', 'GET /notes/:id/backlinks', async function () {
        var d = await T.apiGet('/notes/' + noteId + '/backlinks');
        T.assertHasKey(d, 'data', '/backlinks');
      });

      await T.test('crud', 'notes', 'DELETE /notes/:id', async function () {
        await T.safeDelete('/notes/' + noteId);
        noteId = null;
      });
    }

  };
})();
