using Managing.Application.Abstractions.Repositories;
using Managing.Common;
using Managing.Domain.Workers;
using Managing.Infrastructure.Databases.MongoDb;
using Managing.Infrastructure.Databases.MongoDb.Abstractions;
using Managing.Infrastructure.Databases.MongoDb.Collections;

namespace Managing.Infrastructure.Databases;

public class WorkerRepository : IWorkerRepository
{
    private readonly IMongoRepository<WorkerDto> _workerRepository;
    public WorkerRepository(IMongoRepository<WorkerDto> workerRepository)
    {
        _workerRepository = workerRepository;
    }

    public async Task DisableWorker(Enums.WorkerType workerType)
    {
        var worker = await GetWorker(workerType);
        worker.IsActive = false;
        _workerRepository.Update(worker);
    }

    public async Task EnableWorker(Enums.WorkerType workerType)
    {
        var worker = await GetWorker(workerType);
        worker.IsActive = true;
        _workerRepository.Update(worker);
    }

    public async Task<Worker> GetWorkerAsync(Enums.WorkerType workerType)
    {
        return MongoMappers.Map(await GetWorker(workerType));
    }

    public async Task InsertWorker(Worker worker)
    {
        await _workerRepository.InsertOneAsync(MongoMappers.Map(worker));
    }

    public async Task UpdateWorker(Enums.WorkerType workerType, int executionCount)
    {
        var worker = await GetWorker(workerType);
        worker.ExecutionCount = executionCount;
        worker.LastRunTime = DateTime.UtcNow;
        _workerRepository.Update(worker);
    }

    public IEnumerable<Worker> GetWorkers()
    {
        var workers = _workerRepository.FindAll();
        return workers.Select(MongoMappers.Map);
    }

    private async Task<WorkerDto> GetWorker(Enums.WorkerType workerType)
    {
        return await _workerRepository.FindOneAsync(w => w.WorkerType == workerType);
    }
}
