import { Test, TestingModule } from '@nestjs/testing';
import { VersusService } from './versus.service';
import {GuestsService} from "../../guests/guests.service";
import {GuestsServiceMock} from "../../mocks/guests-service.mock";
import {SharedService} from "../../shared/shared.service";
import {getModelToken} from "@nestjs/mongoose";
import {Versus, VersusDocument} from "../../schemas/versus.schema";
import {Model} from "mongoose";
import {CommandBus, QueryBus} from "@nestjs/cqrs";
import {QueryBusMock} from "../../mocks/querybus.mock";

const mockVersusModel = {
  aggregate: jest.fn().mockReturnThis(),
  exec: jest.fn(),
}

describe('VersusService', () => {
  let service: VersusService;
  let versusModel: Model<Versus>;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        VersusService,
        { provide: GuestsService, useValue: GuestsServiceMock },
        { provide: SharedService, useValue: SharedService },
        { provide: getModelToken(Versus.name), useValue: mockVersusModel },
        { provide: CommandBus, useValue: CommandBus },
        { provide: QueryBus, useValue: QueryBusMock },
      ],
    }).compile();

    service = module.get<VersusService>(VersusService);
    versusModel = module.get<Model<VersusDocument>>(getModelToken(Versus.name));
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  describe('validateVersusTasksAndResetIfNecessary', () => {
    it('should reset all tasks if no remaining', async () => {
      // setup
      mockVersusModel.exec.mockResolvedValue([]);
      const markCompletedSpy = jest.spyOn(service, 'markAllAsUncompleted').mockResolvedValue(null);

      //  act
      await service.validateVersusTasksAndResetIfNecessary();

      // validate
      expect(markCompletedSpy).toHaveBeenCalled();
    });

    it('should not reset tasks if it is presented', async () => {
      mockVersusModel.exec.mockReturnValue(['item1', 'item2']);
      const markCompletedSpy = jest.spyOn(service,'markAllAsUncompleted').mockResolvedValue(null);
      await service.validateVersusTasksAndResetIfNecessary();
      expect(markCompletedSpy).not.toHaveBeenCalled();
    });
  })
});
