import { KnowledgeSourceService } from './knowledge-source.service';

describe('KnowledgeSourceService.remove', () => {
  const repository = {
    create: jest.fn(),
    findByKnowledgeBase: jest.fn(),
    findById: jest.fn(),
    softDelete: jest.fn(),
    updateParseStatus: jest.fn(),
    updateIndexStatus: jest.fn(),
  };

  const importRepo = {
    create: jest.fn(),
  };

  const queue = {
    add: jest.fn(),
  };

  const redis = {
    set: jest.fn(),
  };

  const filesService = {
    deleteFile: jest.fn(),
  };

  let service: KnowledgeSourceService;

  beforeEach(() => {
    jest.clearAllMocks();
    repository.softDelete.mockResolvedValue({ id: 'source-1', deletedAt: new Date() });
    filesService.deleteFile.mockResolvedValue({ success: true });

    service = new KnowledgeSourceService(
      repository as never,
      importRepo as never,
      queue as never,
      redis as never,
      filesService as never,
    );
  });

  it('deletes linked uploaded file before soft deleting source', async () => {
    repository.findById.mockResolvedValue({
      id: 'source-1',
      fileId: 'file-1',
    });

    await service.remove('u1', 'source-1');

    expect(filesService.deleteFile).toHaveBeenCalledWith('u1', 'file-1');
    expect(repository.softDelete).toHaveBeenCalledWith('source-1');
  });

  it('soft deletes source without touching files when no file is linked', async () => {
    repository.findById.mockResolvedValue({
      id: 'source-1',
      fileId: null,
    });

    await service.remove('u1', 'source-1');

    expect(filesService.deleteFile).not.toHaveBeenCalled();
    expect(repository.softDelete).toHaveBeenCalledWith('source-1');
  });
});
