import { describe, it, expect, vi } from 'vitest';
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 ?? '';
}

vi.mock('../requireCodeIgniter.js', () => ({
  requireCodeIgniter: () => ({ root: '/tmp/ci4', adapter: 'codeigniter' }),
}));

vi.mock('../../../lib/runCommand.js', () => ({
  runCommand: vi.fn(async () => ({
    command: 'php',
    args: ['spark', 'migrate:refresh', '--seed'],
    cwd: '/tmp/ci4',
    exitCode: 0,
    timedOut: false,
    failed: false,
    output: 'success',
  })),
}));

describe('spark tool confirm enforcement', () => {
  it('rejects destructive spark commands without confirm', async () => {
    const client = await createInMemoryClient();
    const result = await client.callTool({
      name: 'spark',
      arguments: { command: 'migrate:refresh', args: ['--seed'] },
    });

    const text = firstText(result);
    expect(text).toContain('destructive');
    expect(text).toContain('confirm: true');
  });

  it('allows destructive spark commands with confirm', async () => {
    const client = await createInMemoryClient();
    const result = await client.callTool({
      name: 'spark',
      arguments: { command: 'migrate:refresh', args: ['--seed'], confirm: true },
    });

    const text = firstText(result);
    expect(text).toContain('success');
  });

  it('rejects commands not on the allow-list', async () => {
    const client = await createInMemoryClient();
    const result = await client.callTool({
      name: 'spark',
      arguments: { command: 'serve' },
    });

    const text = firstText(result);
    expect(text).toContain('not on the allow-list');
  });
});
