using Managing.Application.Abstractions.Repositories;
using Managing.Domain.Backtests;
using Managing.Domain.Users;
using Managing.Infrastructure.Databases.MongoDb;
using Managing.Infrastructure.Databases.MongoDb.Abstractions;
using Managing.Infrastructure.Databases.MongoDb.Collections;

namespace Managing.Infrastructure.Databases;

public class BacktestRepository : IBacktestRepository
{
    private readonly IMongoRepository<BacktestDto> _backtestRepository;

    public BacktestRepository(IMongoRepository<BacktestDto> backtestRepository)
    {
        _backtestRepository = backtestRepository;
    }

    // User-specific operations
    public void InsertBacktestForUser(User user, Backtest backtest)
    {
        backtest.User = user;
        _backtestRepository.InsertOne(MongoMappers.Map(backtest));
    }

    public IEnumerable<Backtest> GetBacktestsByUser(User user)
    {
        var backtests = _backtestRepository.AsQueryable()
            .Where(b => b.User != null && b.User.Name == user.Name)
            .ToList();

        return backtests.Select(b => MongoMappers.Map(b));
    }

    public Backtest GetBacktestByIdForUser(User user, string id)
    {
        var backtest = _backtestRepository.FindById(id);

        // Check if backtest exists and belongs to the user
        if (backtest != null && backtest.User != null && backtest.User.Name == user.Name)
        {
            return MongoMappers.Map(backtest);
        }

        return null;
    }

    public void DeleteBacktestByIdForUser(User user, string id)
    {
        var backtest = _backtestRepository.FindById(id);

        if (backtest != null && backtest.User != null && backtest.User.Name == user.Name)
        {
            _backtestRepository.DeleteById(id);
        }
    }

    public void DeleteAllBacktestsForUser(User user)
    {
        var backtests = _backtestRepository.AsQueryable()
            .Where(b => b.User != null && b.User.Name == user.Name)
            .ToList();

        foreach (var backtest in backtests)
        {
            _backtestRepository.DeleteById(backtest.Id.ToString());
        }
    }
}