import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import test from 'node:test';

const testCaseStore = () => readFileSync(join(process.cwd(), 'stores/useTestCaseStore.ts'), 'utf8');
const bugStore = () => readFileSync(join(process.cwd(), 'stores/useBugStore.ts'), 'utf8');

function storeMethodBody(text: string, name: string) {
  const implementationStart = text.indexOf('export const');
  assert.notEqual(implementationStart, -1, 'missing store implementation');
  const start = text.indexOf(`  ${name}:`, implementationStart);
  assert.notEqual(start, -1, `missing store method ${name}`);

  let depth = 0;
  let sawFirstBrace = false;
  for (let i = start; i < text.length; i += 1) {
    const char = text[i];
    if (char === '{') {
      depth += 1;
      sawFirstBrace = true;
    }
    if (char === '}') {
      depth -= 1;
      if (sawFirstBrace && depth === 0) return text.slice(start, i + 1);
    }
  }
  throw new Error(`could not extract store method ${name}`);
}

test('test case store uses domain APIs for version-scoped writes', () => {
  const text = testCaseStore();

  assert.match(text, /from '@\/lib\/domain-api'/);
  assert.match(storeMethodBody(text, 'createTestCase'), /createTestCaseByVersionId\(tc\.versionId,/);
  assert.match(storeMethodBody(text, 'createTestCases'), /createTestCasesByVersionId\(created\[0\]\.versionId,/);
  assert.match(storeMethodBody(text, 'updateTestCase'), /updateTestCaseByVersionId\(versionId, id,/);
  assert.match(storeMethodBody(text, 'changeStatus'), /updateTestCaseStatusByVersionId\(tc\.versionId,/);
  assert.doesNotMatch(storeMethodBody(text, 'createTestCase'), /saveServerData\('test-cases'/);
  assert.doesNotMatch(storeMethodBody(text, 'updateTestCase'), /saveServerData\('test-cases'/);
});

test('bug store uses domain APIs for version-scoped writes', () => {
  const text = bugStore();

  assert.match(text, /from '@\/lib\/domain-api'/);
  assert.match(storeMethodBody(text, 'createBug'), /createBugByVersionId\(bug\.versionId,/);
  assert.match(storeMethodBody(text, 'updateBug'), /updateBugByVersionId\(versionId, id,/);
  assert.match(storeMethodBody(text, 'changeStatus'), /updateBugStatusByVersionId\(bug\.versionId,/);
  assert.match(storeMethodBody(text, 'transferBug'), /transferBugByVersionId\(bug\.versionId,/);
  assert.doesNotMatch(storeMethodBody(text, 'createBug'), /saveServerData\('bugs'/);
  assert.doesNotMatch(storeMethodBody(text, 'updateBug'), /saveServerData\('bugs'/);
});
