using Managing.Application.Abstractions.Repositories;
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 UserRepository : IUserRepository
{
    private readonly IMongoRepository<UserDto> _userRepository;

    public UserRepository(IMongoRepository<UserDto> userRepository)
    {
        _userRepository = userRepository;
    }

    public async Task<User> GetUserByNameAsync(string name)
    {
        var user = await _userRepository.FindOneAsync(u => u.Name == name);
        return MongoMappers.Map(user);
    }

    public async Task InsertUserAsync(User user)
    {
        await _userRepository.InsertOneAsync(MongoMappers.Map(user));
    }

    public async Task UpdateUser(User user)
    {
        try
        {
            var dto = await _userRepository.FindOneAsync(u => u.Name == user.Name);
            dto.Name = user.Name;
            _userRepository.Update(dto);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw new Exception("Cannot update user");
        }
    }
}