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

// Mock child_process
const mockExec = vi.fn();
vi.mock('child_process', () => ({
  exec: (cmd: string, opts: any, cb?: Function) => {
    if (typeof opts === 'function') {
      cb = opts;
    }
    setImmediate(() => {
      const result = mockExec(cmd);
      if (result.error) {
        const err = result.error;
        err.stdout = result.stdout || '';
        err.stderr = result.stderr || '';
        cb?.(err, result.stdout || '', result.stderr || '');
      } else {
        cb?.(null, result.stdout || '', result.stderr || '');
      }
    });
  },
}));

// 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(() => '暂存工作区变更'),
}));

import { gitStashTool } from '../../../../src/tools/git/git_stash.js';
import { getPermissionManager } from '../../../../src/permission/index.js';

describe('gitStashTool - Git Stash 工具', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockExec.mockReturnValue({ stdout: 'Saved working directory', stderr: '' });
  });

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

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

    it('所有参数都是可选的', () => {
      expect(gitStashTool.parameters.action.required).toBe(false);
      expect(gitStashTool.parameters.message.required).toBe(false);
      expect(gitStashTool.parameters.index.required).toBe(false);
      expect(gitStashTool.parameters.include_untracked.required).toBe(false);
    });
  });

  describe('execute - 执行', () => {
    it('默认 push 操作暂存变更', async () => {
      const result = await gitStashTool.execute({});

      expect(result.success).toBe(true);
      expect(mockExec).toHaveBeenCalledWith(expect.stringContaining('git stash push'));
    });

    it('带消息暂存', async () => {
      const result = await gitStashTool.execute({
        message: 'WIP: feature',
      });

      expect(result.success).toBe(true);
      expect(mockExec).toHaveBeenCalledWith(expect.stringContaining('-m'));
    });

    it('包含未跟踪文件', async () => {
      const result = await gitStashTool.execute({
        include_untracked: true,
      });

      expect(result.success).toBe(true);
      expect(mockExec).toHaveBeenCalledWith(expect.stringContaining('-u'));
    });

    it('列出暂存', async () => {
      mockExec.mockReturnValue({
        stdout: 'stash@{0}: WIP on main\nstash@{1}: feature',
        stderr: '',
      });

      const result = await gitStashTool.execute({ action: 'list' });

      expect(result.success).toBe(true);
      expect(mockExec).toHaveBeenCalledWith(expect.stringContaining('git stash list'));
    });

    it('恢复暂存 (pop)', async () => {
      mockExec.mockReturnValue({ stdout: '', stderr: '' });

      const result = await gitStashTool.execute({ action: 'pop' });

      expect(result.success).toBe(true);
      expect(result.output).toContain('暂存已恢复并删除');
      expect(mockExec).toHaveBeenCalledWith(expect.stringContaining('git stash pop'));
    });

    it('应用暂存 (apply)', async () => {
      mockExec.mockReturnValue({ stdout: '', stderr: '' });

      const result = await gitStashTool.execute({ action: 'apply' });

      expect(result.success).toBe(true);
      expect(result.output).toContain('暂存已恢复');
      expect(mockExec).toHaveBeenCalledWith(expect.stringContaining('git stash apply'));
    });

    it('删除暂存 (drop)', async () => {
      mockExec.mockReturnValue({ stdout: '', stderr: '' });

      const result = await gitStashTool.execute({ action: 'drop', index: 1 });

      expect(result.success).toBe(true);
      expect(mockExec).toHaveBeenCalledWith(expect.stringContaining('git stash drop stash@{1}'));
    });

    it('清除所有暂存', async () => {
      mockExec.mockReturnValue({ stdout: '', stderr: '' });

      const result = await gitStashTool.execute({ action: 'clear' });

      expect(result.success).toBe(true);
      expect(result.output).toContain('所有暂存已清除');
      expect(mockExec).toHaveBeenCalledWith(expect.stringContaining('git stash clear'));
    });

    it('显示暂存内容', async () => {
      mockExec.mockReturnValue({ stdout: 'diff --git a/file.ts', stderr: '' });

      const result = await gitStashTool.execute({ action: 'show' });

      expect(result.success).toBe(true);
      expect(mockExec).toHaveBeenCalledWith(expect.stringContaining('git stash show -p'));
    });

    it('未知操作返回错误', async () => {
      const result = await gitStashTool.execute({ action: 'unknown' });

      expect(result.success).toBe(false);
      expect(result.error).toContain('未知操作');
    });

    it('没有变更时返回友好错误', async () => {
      // 确保权限通过
      vi.mocked(getPermissionManager).mockReturnValue({
        checkGitPermission: vi.fn().mockResolvedValue({ allowed: true }),
      } as any);
      mockExec.mockReturnValue({
        error: new Error('Command failed'),
        stdout: '',
        stderr: 'No local changes to save',
      });

      const result = await gitStashTool.execute({});

      expect(result.success).toBe(false);
      expect(result.error).toContain('没有需要暂存的变更');
    });

    it('恢复冲突时返回友好错误', async () => {
      // 确保权限通过
      vi.mocked(getPermissionManager).mockReturnValue({
        checkGitPermission: vi.fn().mockResolvedValue({ allowed: true }),
      } as any);
      mockExec.mockReturnValue({
        error: new Error('Command failed'),
        stdout: '',
        stderr: 'CONFLICT (content): Merge conflict',
      });

      const result = await gitStashTool.execute({ action: 'pop' });

      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 gitStashTool.execute({});

      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 gitStashTool.execute({});

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