import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';

const here = path.dirname(fileURLToPath(import.meta.url));

void test('projectState: list/get after delete invalidates in-flight initial load (epoch guard)', () => {
  const src = fs.readFileSync(path.join(here, 'projectState.ts'), 'utf8');
  assert.match(src, /projectDataEpochRef/);
  assert.match(src, /const epoch = \+\+projectDataEpochRef\.current/);
  assert.match(src, /if \(projectDataEpochRef\.current !== epoch\) return/);
  assert.match(
    src,
    /const deleteProject = async[\s\S]+?projectDataEpochRef\.current \+= 1[\s\S]+?await api\.invoke/,
  );
  assert.match(
    src,
    /const openProject = async[\s\S]+?projectDataEpochRef\.current \+= 1[\s\S]+?const epoch = projectDataEpochRef\.current[\s\S]+?openInFlightRef\.current = null[\s\S]+?if \(projectDataEpochRef\.current !== epoch\)/,
  );
  assert.match(src, /openInFlightRef\.current = null[\s\S]+?openingProjectId: null/);
  assert.match(src, /const refreshProjects = async \(\) => \{[\s\S]+?projectDataEpochRef\.current \+= 1/);
});

void test('projectState: createScene clears creatingScene and in-flight ref', () => {
  const src = fs.readFileSync(path.join(here, 'projectState.ts'), 'utf8');
  assert.match(src, /createSceneInFlightRef\.current = job;/);
  assert.match(src, /creatingScene: false/);
  assert.doesNotMatch(src, /createSceneInFlightRef\.current = job\.finally/);
});

void test('ipc router: project.list does not require license', () => {
  const routerSrc = fs.readFileSync(path.join(here, '..', '..', '..', 'main', 'ipc', 'router.ts'), 'utf8');
  assert.match(routerSrc, /if \(channel === ipcChannels\.project\.list\) return false/);
});

void test('projectState: openProject не выбирает сцену (selectedSceneId: null)', () => {
  const src = fs.readFileSync(path.join(here, 'projectState.ts'), 'utf8');
  assert.match(
    src,
    /const openProject = async[\s\S]+?openingProjectId: id, selectedSceneId: null[\s\S]+?selectedSceneId: null,\s*openingProjectId: null/,
  );
});
