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

const source = () => readFileSync(join(process.cwd(), 'stores/useProductStore.ts'), 'utf8');

function storeMethodBody(text: string, name: string) {
  const start = text.indexOf(`\n  ${name}: async`);
  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('product root store imports domain root write helpers', () => {
  assert.match(source(), /from '@\/lib\/domain-api'/);
});

test('project mutations use domain APIs instead of products-overview AppData saves', () => {
  const text = source();
  const createProject = storeMethodBody(text, 'createProject');
  const updateProject = storeMethodBody(text, 'updateProject');
  const deleteProject = storeMethodBody(text, 'deleteProject');

  assert.match(createProject, /createProjectByProductId\(productId, data\)/);
  assert.match(updateProject, /updateProjectByProductId\(productId, projectId, data\)/);
  assert.match(deleteProject, /deleteProjectByProductId\(productId, projectId\)/);
  assert.doesNotMatch(createProject, /saveStoredOverview\(updated\)/);
  assert.doesNotMatch(updateProject, /saveStoredOverview\(updated\)/);
  assert.doesNotMatch(deleteProject, /saveStoredOverview\(updated\)/);
});

test('version mutations use domain APIs instead of products-overview AppData saves', () => {
  const text = source();
  const createVersion = storeMethodBody(text, 'createVersion');
  const updateVersion = storeMethodBody(text, 'updateVersion');
  const deleteVersion = storeMethodBody(text, 'deleteVersion');

  assert.match(createVersion, /createVersionByProductId\(productId, data\)/);
  assert.match(updateVersion, /updateVersionByProductId\(productId, versionId, data\)/);
  assert.match(deleteVersion, /deleteVersionByProductId\(productId, versionId\)/);
  assert.doesNotMatch(createVersion, /saveStoredOverview\(updated\)/);
  assert.doesNotMatch(updateVersion, /saveStoredOverview\(updated\)/);
  assert.doesNotMatch(deleteVersion, /saveStoredOverview\(updated\)/);
});
