import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';

function sourceFiles(dir: string): string[] {
  return readdirSync(dir).flatMap((entry) => {
    const path = join(dir, entry);
    return statSync(path).isDirectory() ? sourceFiles(path) : path.endsWith('.ts') ? [path] : [];
  });
}

const SQL_TABLES = /\bcart_|\binventory_|\bpricing_|\bshipping_|\bpromotions_|\busers_/;

describe('checkout persistence boundary', () => {
  it('does not reference other module tables in code or SQL', () => {
    const dir = new URL('..', import.meta.url);
    for (const file of sourceFiles(dir.pathname)) {
      const source = readFileSync(file, 'utf8');
      // Allow imports of public interfaces from sibling modules but not
      // hardcoded SQL table references.
      expect(source).not.toMatch(SQL_TABLES);
    }
  });

  it('does not import internals of sibling modules', () => {
    const dir = new URL('..', import.meta.url);
    for (const file of sourceFiles(dir.pathname)) {
      const source = readFileSync(file, 'utf8');
      expect(source).not.toMatch(
        /modules\/(cart|inventory|pricing|promotions|shipping|orders)\/(api|application|infrastructure|tests)/,
      );
    }
  });
});
