import { describe, it, expect, beforeEach, vi } from 'vitest';

// 定义一个可控的 mock
let mockExecAsyncResult: { stdout: string; stderr: string } | Error = {
  stdout: '',
  stderr: '',
};

// Mock child_process
vi.mock('child_process', () => ({
  exec: vi.fn(),
}));

// Mock util
vi.mock('util', () => ({
  promisify: vi.fn(() => vi.fn(async () => {
    if (mockExecAsyncResult instanceof Error) {
      throw mockExecAsyncResult;
    }
    return mockExecAsyncResult;
  })),
}));

// Mock permission manager
vi.mock('../../../../src/permission/index.js', () => ({
  getPermissionManager: vi.fn(() => ({
    checkGitPermission: vi.fn().mockResolvedValue({
      allowed: true,
      action: 'allow',
    }),
  })),
}));

// Mock loadDescription
vi.mock('../../../../src/tools/load_description.js', () => ({
  loadDescription: vi.fn(() => 'Git add 命令'),
}));

import { gitAddTool } from '../../../../src/tools/git/git_add.js';
import { getPermissionManager } from '../../../../src/permission/index.js';

describe('gitAddTool - Git Add 工具', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockExecAsyncResult = {
      stdout: '',
      stderr: '',
    };
  });

  describe('工具定义', () => {
    it('有正确的名称', () => {
      expect(gitAddTool.name).toBe('git_add');
    });

    it('有正确的元数据', () => {
      expect(gitAddTool.metadata.category).toBe('git');
      expect(gitAddTool.metadata.keywords).toContain('add');
      expect(gitAddTool.metadata.keywords).toContain('stage');
    });

    it('定义了可选参数', () => {
      expect(gitAddTool.parameters.files.required).toBe(false);
      expect(gitAddTool.parameters.all.required).toBe(false);
      expect(gitAddTool.parameters.update.required).toBe(false);
    });
  });

  describe('execute - 执行', () => {
    it('暂存所有文件 (all: true)', async () => {
      mockExecAsyncResult = { stdout: '', stderr: '' };

      const result = await gitAddTool.execute({ all: true });

      expect(result.success).toBe(true);
      expect(result.output).toContain('文件已暂存');
    });

    it('暂存指定文件', async () => {
      mockExecAsyncResult = { stdout: '', stderr: '' };

      const result = await gitAddTool.execute({
        files: ['file1.txt', 'file2.txt'],
      });

      expect(result.success).toBe(true);
    });

    it('暂存单个文件（字符串）', async () => {
      mockExecAsyncResult = { stdout: '', stderr: '' };

      const result = await gitAddTool.execute({ files: 'single.txt' });

      expect(result.success).toBe(true);
    });

    it('使用 update 选项', async () => {
      mockExecAsyncResult = { stdout: '', stderr: '' };

      const result = await gitAddTool.execute({ update: true });

      expect(result.success).toBe(true);
    });

    it('无参数返回错误', async () => {
      const result = await gitAddTool.execute({});

      expect(result.success).toBe(false);
      expect(result.error).toContain('请指定要暂存的文件');
    });

    it('权限被拒绝时返回错误', async () => {
      vi.mocked(getPermissionManager).mockReturnValue({
        checkGitPermission: vi.fn().mockResolvedValue({
          allowed: false,
          action: 'deny',
          reason: '操作不被允许',
        }),
      } as any);

      const result = await gitAddTool.execute({ all: true });

      expect(result.success).toBe(false);
      expect(result.error).toContain('权限被拒绝');
    });

    it('需要确认时返回提示', async () => {
      vi.mocked(getPermissionManager).mockReturnValue({
        checkGitPermission: vi.fn().mockResolvedValue({
          allowed: false,
          action: 'ask',
          needsConfirmation: true,
        }),
      } as any);

      const result = await gitAddTool.execute({ all: true });

      expect(result.success).toBe(false);
      expect(result.error).toContain('需要用户确认');
    });

    it('命令执行失败返回错误', async () => {
      vi.mocked(getPermissionManager).mockReturnValue({
        checkGitPermission: vi.fn().mockResolvedValue({
          allowed: true,
          action: 'allow',
        }),
      } as any);
      mockExecAsyncResult = Object.assign(
        new Error('Command failed'),
        { stdout: '', stderr: 'fatal: not a git repository', message: 'Command failed' }
      );

      const result = await gitAddTool.execute({ all: true });

      expect(result.success).toBe(false);
      expect(result.error).toContain('not a git repository');
    });
  });
});
