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

// Mock fs/promises
vi.mock('fs/promises', () => ({
  stat: vi.fn(),
  unlink: vi.fn().mockResolvedValue(undefined),
  rmdir: vi.fn().mockResolvedValue(undefined),
  rm: vi.fn().mockResolvedValue(undefined),
  readdir: vi.fn().mockResolvedValue([]),
}));

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

// Mock loadDescription
vi.mock('../../../../src/tools/load_description.js', () => ({
  loadDescription: vi.fn(() => '删除文件'),
}));

import { deleteFileTool } from '../../../../src/tools/filesystem/delete_file.js';
import * as fs from 'fs/promises';
import { getPermissionManager } from '../../../../src/permission/index.js';

describe('deleteFileTool - 文件删除工具', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

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

    it('有正确的元数据', () => {
      expect(deleteFileTool.metadata.category).toBe('filesystem');
      expect(deleteFileTool.metadata.keywords).toContain('delete');
      expect(deleteFileTool.metadata.keywords).toContain('remove');
      expect(deleteFileTool.metadata.keywords).toContain('rm');
    });

    it('定义了必需的 path 参数', () => {
      expect(deleteFileTool.parameters.path.required).toBe(true);
    });

    it('定义了可选的 recursive 参数', () => {
      expect(deleteFileTool.parameters.recursive.required).toBe(false);
    });
  });

  describe('execute - 执行', () => {
    it('成功删除文件', async () => {
      vi.mocked(fs.stat).mockResolvedValue({
        isDirectory: () => false,
      } as any);

      const result = await deleteFileTool.execute({ path: 'file.txt' });

      expect(result.success).toBe(true);
      expect(result.output).toContain('已删除文件');
      expect(fs.unlink).toHaveBeenCalled();
    });

    it('删除空目录', async () => {
      vi.mocked(fs.stat).mockResolvedValue({
        isDirectory: () => true,
      } as any);
      vi.mocked(fs.readdir).mockResolvedValue([]);

      const result = await deleteFileTool.execute({ path: 'empty_dir' });

      expect(result.success).toBe(true);
      expect(result.output).toContain('已删除目录');
      expect(fs.rmdir).toHaveBeenCalled();
    });

    it('非空目录无 recursive 返回错误', async () => {
      vi.mocked(fs.stat).mockResolvedValue({
        isDirectory: () => true,
      } as any);
      vi.mocked(fs.readdir).mockResolvedValue(['file1.txt', 'file2.txt'] as any);

      const result = await deleteFileTool.execute({ path: 'nonempty_dir' });

      expect(result.success).toBe(false);
      expect(result.error).toContain('目录不为空');
      expect(result.error).toContain('recursive: true');
    });

    it('递归删除非空目录', async () => {
      vi.mocked(fs.stat).mockResolvedValue({
        isDirectory: () => true,
      } as any);

      const result = await deleteFileTool.execute({
        path: 'nonempty_dir',
        recursive: true,
      });

      expect(result.success).toBe(true);
      expect(result.output).toContain('已删除目录');
      expect(fs.rm).toHaveBeenCalledWith(
        expect.any(String),
        { recursive: true }
      );
    });

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

      const result = await deleteFileTool.execute({ path: '/protected/file' });

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

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

      const result = await deleteFileTool.execute({ path: 'important.txt' });

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

    it('文件不存在返回错误', async () => {
      vi.mocked(getPermissionManager).mockReturnValue({
        checkFilePermission: vi.fn().mockResolvedValue({ allowed: true }),
      } as any);

      vi.mocked(fs.stat).mockRejectedValue(new Error('ENOENT'));

      const result = await deleteFileTool.execute({ path: 'nonexistent.txt' });

      expect(result.success).toBe(false);
      expect(result.error).toContain('ENOENT');
    });

    it('传递正确参数给权限检查', async () => {
      const mockCheck = vi.fn().mockResolvedValue({ allowed: true });
      vi.mocked(getPermissionManager).mockReturnValue({
        checkFilePermission: mockCheck,
      } as any);
      vi.mocked(fs.stat).mockResolvedValue({ isDirectory: () => false } as any);

      await deleteFileTool.execute({ path: 'test.txt' });

      expect(mockCheck).toHaveBeenCalledWith(
        expect.objectContaining({
          operation: 'delete',
        })
      );
    });
  });
});
