using Yuna.Website.Server.Model;
using Yuna.Website.Server.Storage.Repositories.User;

namespace Yuna.Website.Server.Services.UserService
{
    public class UserService : IUserService
    {
        private readonly IUserRepository _userRepository;
        public UserService(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }

        public async Task<User?> Create(User user)
        {
            var existingUser = await _userRepository.GetByUsername(user.UserName);
            if (existingUser is not null) return null;

            var result = await _userRepository.Create(user);
            return result;
        }

        public async Task<User?> Delete(long id)
        {
            var user = await _userRepository.GetById(id);
            if (user is null) return null;

            var result = await _userRepository.Delete(id);
            return user;
        }

        public async Task<User?> GetById(long id)
        {
            var result = await _userRepository.GetById(id);
            return result;
        }

        public async Task<User?> GetByUsername(string username)
        {
            var user = await _userRepository.GetByUsername(username);
            return user;
        }

        public async Task<IReadOnlyList<User>> GetList()
        {
            var result = await _userRepository.GetList();
            return result ?? [];
        }

        public async Task<User?> Update(User user)
        {
            var userFromDb = await _userRepository.GetById(user.Id);
            if(userFromDb is null) return null;

            return await _userRepository.Update(user);
        }
    }
}
