'use strict';

// B16 / QA-B16-01: the external version check must be opt-out-able. When the
// `update_check_enabled` setting is 'false', checkForUpdates must make NO network
// request and report `disabled`. Default (unset/'true') performs the check.
const test = require('node:test');
const assert = require('node:assert/strict');
const os = require('node:os');
const path = require('node:path');
const fs = require('node:fs');

const dbPath = path.join(os.tmpdir(), `bill-tracker-updatecheck-test-${process.pid}.sqlite`);
process.env.DB_PATH = dbPath;

const { getDb, setSetting, closeDb } = require('../db/database');
const svc = require('../services/updateCheckService');

test('disabled: makes no external request and returns disabled', async () => {
  getDb();
  setSetting('update_check_enabled', 'false');
  assert.equal(svc.updateCheckEnabled(), false);

  const orig = global.fetch;
  let called = false;
  global.fetch = async () => { called = true; throw new Error('fetch must not be called when disabled'); };
  try {
    const r = await svc.checkForUpdates(true);
    assert.equal(r.disabled, true, 'reports disabled');
    assert.equal(called, false, 'no external fetch when disabled');
  } finally {
    global.fetch = orig;
  }
});

test('enabled (default): performs the version check', async () => {
  setSetting('update_check_enabled', 'true');
  assert.equal(svc.updateCheckEnabled(), true);

  const orig = global.fetch;
  global.fetch = async () => ({
    ok: true,
    status: 200,
    json: async () => ({ tag_name: 'v99.0.0', html_url: 'https://example/rel', published_at: '2026-01-01' }),
  });
  try {
    const r = await svc.checkForUpdates(true);
    assert.notEqual(r.disabled, true);
    assert.equal(r.latest_version, '99.0.0');
    assert.equal(r.has_update, true);
  } finally {
    global.fetch = orig;
  }
});

test.after(() => {
  closeDb();
  for (const suffix of ['', '-wal', '-shm']) {
    try { fs.rmSync(dbPath + suffix); } catch { /* ignore */ }
  }
});
