import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

import { findProjectMarker, writeProjectMarker, MARKER_FILENAME } from '../../src/utils/project-marker.js';

describe('project-marker', () => {
  let tmp: string;

  beforeEach(async () => {
    tmp = await mkdtemp(join(tmpdir(), 'mcpctl-marker-'));
  });

  afterEach(async () => {
    await rm(tmp, { recursive: true, force: true });
  });

  it('finds marker in cwd', async () => {
    await writeFile(join(tmp, MARKER_FILENAME), 'demo\n');
    const result = await findProjectMarker(tmp, '/never-exists');
    expect(result?.project).toBe('demo');
    expect(result?.markerPath).toBe(join(tmp, MARKER_FILENAME));
  });

  it('walks up to find marker', async () => {
    const sub = join(tmp, 'a', 'b', 'c');
    await mkdir(sub, { recursive: true });
    await writeFile(join(tmp, MARKER_FILENAME), 'parent-project');
    const result = await findProjectMarker(sub, '/never-exists');
    expect(result?.project).toBe('parent-project');
  });

  it('returns null when no marker exists', async () => {
    const sub = join(tmp, 'a', 'b');
    await mkdir(sub, { recursive: true });
    const result = await findProjectMarker(sub, '/never-exists');
    expect(result).toBeNull();
  });

  it('stops at user home directory', async () => {
    // Use tmp itself as the "home" — the walk should not go above it.
    const sub = join(tmp, 'projects', 'demo');
    await mkdir(sub, { recursive: true });
    // Marker would be at /tmp's parent (above home) — should not be found.
    const result = await findProjectMarker(sub, tmp);
    expect(result).toBeNull();
  });

  it('trims trailing whitespace from the project name', async () => {
    await writeFile(join(tmp, MARKER_FILENAME), '  demo  \nignored\n');
    const result = await findProjectMarker(tmp, '/never-exists');
    expect(result?.project).toBe('demo');
  });

  it('rejects empty marker file', async () => {
    await writeFile(join(tmp, MARKER_FILENAME), '\n');
    const result = await findProjectMarker(tmp, '/never-exists');
    expect(result).toBeNull();
  });

  it('writeProjectMarker writes the file with a trailing newline', async () => {
    const path = await writeProjectMarker(tmp, 'demo');
    expect(path).toBe(join(tmp, MARKER_FILENAME));
    const result = await findProjectMarker(tmp, '/never-exists');
    expect(result?.project).toBe('demo');
  });
});
