import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createInMemoryClient } from '../../../test/mcpServer.js';

function firstText(result: unknown): string {
  const r = result as { content?: Array<{ text?: string }> } | undefined;
  return r?.content?.[0]?.text ?? '';
}

describe('docker generate + push confirm gates', () => {
  let tmpDir: string;
  let originalRoot: string;

  beforeEach(async () => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'web-dev-mcp-docker-gen-'));
    fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({ name: 'app', dependencies: { react: '^18' } }));
    const config = await import('../../../config.js');
    originalRoot = config.config.workspaceRoot;
    (config.config as { workspaceRoot: string }).workspaceRoot = tmpDir;
  });

  afterEach(async () => {
    const config = await import('../../../config.js');
    (config.config as { workspaceRoot: string }).workspaceRoot = originalRoot;
    fs.rmSync(tmpDir, { recursive: true, force: true });
  });

  it('generate_dockerfile writes a Dockerfile', async () => {
    const client = await createInMemoryClient();
    const result = await client.callTool({ name: 'generate_dockerfile', arguments: {} });
    const text = firstText(result);
    expect(text).toContain('Dockerfile');
    expect(fs.existsSync(path.join(tmpDir, 'Dockerfile'))).toBe(true);
  });

  it('generate_compose writes docker-compose.yml', async () => {
    const client = await createInMemoryClient();
    const result = await client.callTool({ name: 'generate_compose', arguments: {} });
    expect(firstText(result)).toContain('docker-compose.yml');
    expect(fs.existsSync(path.join(tmpDir, 'docker-compose.yml'))).toBe(true);
  });

  it('docker_push_image requires confirm', async () => {
    const client = await createInMemoryClient();
    const result = await client.callTool({
      name: 'docker_push_image',
      arguments: { image: 'my-app:latest' },
    });
    expect(firstText(result)).toContain('confirm: true');
  });

  it('generate_sail requires confirm', async () => {
    const client = await createInMemoryClient();
    const result = await client.callTool({ name: 'generate_sail', arguments: {} });
    expect(firstText(result)).toContain('confirm: true');
  });
});
