import assert from 'node:assert/strict';
import test from 'node:test';
import {
  defaultMindSpaceConfig,
  ensureMindSpaceConfig,
  loadMindSpaceConfig,
  updateMindSpaceConfig,
} from './mindspace-config.mjs';

test('defaultMindSpaceConfig falls back to env or 5', () => {
  assert.equal(defaultMindSpaceConfig({ MINDSPACE_FREE_PUBLIC_PAGE_LIMIT: '8' }).publicPageLimit, 8);
  assert.equal(defaultMindSpaceConfig({ MINDSPACE_FREE_PUBLIC_PAGE_LIMIT: '0' }).publicPageLimit, 5);
});

test('ensureMindSpaceConfig seeds the default row only when empty', async () => {
  const calls = [];
  const pool = {
    async query(sql, params) {
      calls.push({ sql, params });
      if (sql.includes('COUNT(*) AS count')) return [[{ count: 0 }]];
      return [[]];
    },
  };

  await ensureMindSpaceConfig(pool, { env: { MINDSPACE_FREE_PUBLIC_PAGE_LIMIT: '9' } });

  assert.equal(calls.length, 3);
  assert.match(calls[0].sql, /CREATE TABLE IF NOT EXISTS mindspace_config/);
  assert.match(calls[2].sql, /INSERT INTO mindspace_config/);
  assert.deepEqual(calls[2].params.slice(0, 3), ['public_page_limit', '9', '公开页面数量上限']);
});

test('loadMindSpaceConfig merges stored config with fallback', async () => {
  const pool = {
    async query(sql) {
      if (sql.includes('FROM mindspace_config')) {
        return [[
          { key: 'public_page_limit', value: '12' },
          { key: 'ignored', value: '99' },
        ]];
      }
      return [[]];
    },
  };

  const config = await loadMindSpaceConfig(pool, { env: { MINDSPACE_FREE_PUBLIC_PAGE_LIMIT: '7' } });
  assert.equal(config.publicPageLimit, 12);
});

test('updateMindSpaceConfig persists a positive integer limit', async () => {
  const calls = [];
  const pool = {
    async query(sql, params) {
      calls.push({ sql, params });
      if (sql.includes('CREATE TABLE IF NOT EXISTS mindspace_config')) return [[]];
      if (sql.includes('FROM mindspace_config')) {
        return [[{ key: 'public_page_limit', value: '15' }]];
      }
      return [[]];
    },
  };

  const config = await updateMindSpaceConfig(pool, { publicPageLimit: 15 });
  assert.equal(config.publicPageLimit, 15);
  assert.equal(calls.some(({ sql }) => sql.includes('ON DUPLICATE KEY UPDATE')), true);
});
