import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { detectWorkspace, resolvePackage, summarizeWorkspace } from '../detect.js';

describe('detectWorkspace', () => {
  let tmpDir: string;

  beforeEach(() => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'web-dev-mcp-ws-'));
  });

  afterEach(() => {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  });

  it('includes the root and apps/* packages', () => {
    fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({ name: 'root', private: true }));
    fs.mkdirSync(path.join(tmpDir, 'apps', 'web'), { recursive: true });
    fs.writeFileSync(
      path.join(tmpDir, 'apps', 'web', 'package.json'),
      JSON.stringify({ name: 'web', dependencies: { react: '^18.0' } }),
    );

    const workspace = detectWorkspace(tmpDir);
    const summary = summarizeWorkspace(workspace);
    expect(summary.packageCount).toBeGreaterThanOrEqual(2);
    const names = workspace.packages.map((p) => p.name);
    expect(names).toContain('web');
  });

  it('resolvePackage finds by name and relative path', () => {
    fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({ name: 'root' }));
    fs.mkdirSync(path.join(tmpDir, 'packages', 'api'), { recursive: true });
    fs.writeFileSync(path.join(tmpDir, 'packages', 'api', 'package.json'), JSON.stringify({ name: 'api' }));

    const byName = resolvePackage(tmpDir, 'api');
    expect(byName.pkg.relativePath.replace(/\\/g, '/')).toBe('packages/api');

    const byPath = resolvePackage(tmpDir, 'packages/api');
    expect(byPath.pkg.name).toBe('api');
  });

  it('resolvePackage throws for unknown packages', () => {
    fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({ name: 'root' }));
    expect(() => resolvePackage(tmpDir, 'missing')).toThrow(/Unknown package/);
  });
});
