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

const planStore = () => readFileSync(join(process.cwd(), 'stores/useVersionPlanStore.ts'), 'utf8');
const taskStore = () => readFileSync(join(process.cwd(), 'stores/useDevTaskStore.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('version plan store uses domain APIs for version-scoped writes', () => {
  const text = planStore();

  assert.match(text, /from '@\/lib\/domain-api'/);
  assert.match(storeMethodBody(text, 'createPlan'), /createVersionPlanByVersionId\(plan\.versionId,/);
  assert.match(storeMethodBody(text, 'updatePlan'), /updateVersionPlanByVersionId\(versionId, id,/);
  assert.match(storeMethodBody(text, 'completePlan'), /completeVersionPlanByVersionId\(versionId, id,/);
  assert.doesNotMatch(storeMethodBody(text, 'createPlan'), /saveServerData\('version-plans'/);
  assert.doesNotMatch(storeMethodBody(text, 'updatePlan'), /saveServerData\('version-plans'/);
});

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

  assert.match(text, /from '@\/lib\/domain-api'/);
  assert.match(storeMethodBody(text, 'createTask'), /createDevTaskByVersionId\(task\.versionId,/);
  assert.match(storeMethodBody(text, 'updateTask'), /updateDevTaskByVersionId\(versionId, id,/);
  assert.match(storeMethodBody(text, 'changeStatus'), /updateDevTaskStatusByVersionId\(task\.versionId,/);
  assert.match(storeMethodBody(text, 'setBlocked'), /setDevTaskBlockedByVersionId\(task\.versionId,/);
  assert.doesNotMatch(storeMethodBody(text, 'createTask'), /saveServerData\('dev-tasks'/);
  assert.doesNotMatch(storeMethodBody(text, 'updateTask'), /saveServerData\('dev-tasks'/);
});
