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

function store(name: string) {
  return readFileSync(join(process.cwd(), `stores/${name}`), '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('member and dictionary stores use domain APIs as primary writes', () => {
  const members = store('useMemberStore.ts');
  const categories = store('useTaskCategoryStore.ts');

  assert.match(members, /from '@\/lib\/domain-api'/);
  assert.match(storeMethodBody(members, 'createMember'), /createMemberDomain\(member,/);
  assert.match(storeMethodBody(members, 'updateMember'), /updateMemberDomain\(id,/);
  assert.match(storeMethodBody(members, 'deleteMember'), /deleteMemberDomain\(id\)/);

  assert.match(categories, /from '@\/lib\/domain-api'/);
  assert.match(storeMethodBody(categories, 'addCategory'), /createTaskCategoryDomain\(item\)/);
  assert.match(storeMethodBody(categories, 'updateCategory'), /updateTaskCategoryDomain\(id,/);
  assert.match(storeMethodBody(categories, 'deleteCategory'), /deleteTaskCategoryDomain\(id\)/);
});

test('evidence stores use append-style domain APIs as primary writes', () => {
  const worklogs = store('useTaskWorklogStore.ts');
  const overtime = store('useOvertimeStore.ts');
  const activities = store('useWorkActivityStore.ts');

  assert.match(storeMethodBody(worklogs, 'addWorklog'), /createTaskWorklogDomain\(item\)/);
  assert.match(storeMethodBody(overtime, 'createRecord'), /createOvertimeRecordDomain\(record\)/);
  assert.match(storeMethodBody(activities, 'addActivity'), /createWorkActivityDomain\(item\)/);

  assert.doesNotMatch(storeMethodBody(worklogs, 'addWorklog'), /saveServerData\('task-worklogs'/);
  assert.doesNotMatch(storeMethodBody(overtime, 'createRecord'), /saveServerData\('overtime'/);
  assert.doesNotMatch(storeMethodBody(activities, 'addActivity'), /saveServerData\('work-activities'/);
});
