import { describe, test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';

// M0-6: quick-import must resolve its exports dir under the EXTERNAL data root,
// and the manual import command it prints must no longer pin ANALYTICS_ROOT to
// the in-plugin tree. The module's executable body (browser open + poll timer)
// sits behind a standalone guard, so importing it for tests is side-effect-free.
// LINKEDIN_STUDIO_DATA is stubbed before the dynamic import (EXPORTS_DIR binds at
// load). Pattern: data-root.test.mjs env-stub + queue-manager.test.mjs.
describe('quick-import — external data root + de-pinned command (M0-6)', () => {
  let dataDir, mod;
  const saved = { LINKEDIN_STUDIO_DATA: process.env.LINKEDIN_STUDIO_DATA };

  before(async () => {
    dataDir = mkdtempSync(join(tmpdir(), 'lis-quickimport-'));
    process.env.LINKEDIN_STUDIO_DATA = dataDir;
    mod = await import('../quick-import.mjs');
  });

  after(() => {
    if (dataDir && existsSync(dataDir)) rmSync(dataDir, { recursive: true, force: true });
    if (saved.LINKEDIN_STUDIO_DATA === undefined) delete process.env.LINKEDIN_STUDIO_DATA;
    else process.env.LINKEDIN_STUDIO_DATA = saved.LINKEDIN_STUDIO_DATA;
  });

  test('EXPORTS_DIR resolves under <dataDir>/analytics/exports', () => {
    assert.equal(mod.EXPORTS_DIR, join(dataDir, 'analytics', 'exports'));
  });

  test('the printed import command no longer pins a bare in-plugin assets/analytics path', () => {
    const cmd = mod.buildImportCommand('/plugin/root', 'export.csv');
    assert.ok(
      !cmd.includes('assets/analytics'),
      'manual command must not pin ANALYTICS_ROOT to the in-plugin assets/analytics tree',
    );
    assert.ok(
      cmd.includes('scripts/analytics/src/cli.ts'),
      'manual command must still invoke the in-plugin tsx CLI',
    );
    assert.ok(cmd.includes('export.csv'));
  });
});
