using Managing.Application.Abstractions.Repositories;
using Managing.Domain.Workflows.Synthetics;
using Managing.Infrastructure.Databases.MongoDb;
using Managing.Infrastructure.Databases.MongoDb.Abstractions;
using Managing.Infrastructure.Databases.MongoDb.Collections;

namespace Managing.Infrastructure.Databases;

public class WorkflowRepository : IWorkflowRepository
{
    private readonly IMongoRepository<WorkflowDto> _workflowRepository;

    public WorkflowRepository(IMongoRepository<WorkflowDto> workflowRepository)
    {
        _workflowRepository = workflowRepository;
    }
    public bool DeleteWorkflow(string name)
    {
        var workflow = _workflowRepository.FindOne(m => m.Name == name);
        _workflowRepository.DeleteById(workflow.Id.ToString());
        return true;
    }

    public async Task InsertWorkflow(SyntheticWorkflow workflow)
    {
        await _workflowRepository.InsertOneAsync(MongoMappers.Map(workflow));
    }

    public async Task UpdateWorkflow(SyntheticWorkflow workflow)
    {
        var w = await _workflowRepository.FindOneAsync(m => m.Name == workflow.Name);
        var dto = MongoMappers.Map(workflow);
        dto.Id = w.Id;
        _workflowRepository.Update(dto);
    }

    public async Task<SyntheticWorkflow> GetWorkflow(string name)
    {
        var workflow = await _workflowRepository.FindOneAsync(m => m.Name == name);
        return MongoMappers.Map(workflow);
    }

    public IEnumerable<SyntheticWorkflow> GetWorkflows()
    {
        var workflows = _workflowRepository.FindAll();
        return workflows.Select(m => MongoMappers.Map(m));
    }
}
