using data.Exception;
using data.RemoteData.RemoteDataBase;
using data.RemoteData.RemoteDataBase.DAO;
using domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;

namespace data.Repository
{
    public class SQLUserRepositoryImpl : IUserRepository
    {
        private readonly RemoteDatabaseContext _remoteDatabaseContext;

        public SQLUserRepositoryImpl(RemoteDatabaseContext remoteDatabaseContext)
        {
            _remoteDatabaseContext = remoteDatabaseContext;
        }

        
        public IEnumerable<UserLocalEnity> GetAllUsers => _remoteDatabaseContext.Users
            .Select(u => new UserLocalEnity
            {
                Guid = u.Guid,
                FIO = u.FIO,
                GroupID = u.GroupID
            })
            .ToList();

        public bool RemoveUserByGuid(Guid userGuid)
        {
            var user = _remoteDatabaseContext.Users.FirstOrDefault(u => u.Guid == userGuid);
            if (user == null) throw new UserNotFoundException(userGuid);

            _remoteDatabaseContext.Users.Remove(user);
            _remoteDatabaseContext.SaveChanges(); 
            return true;
        }

        public UserLocalEnity? UpdateUser(UserLocalEnity user)
        {
            var existingUser = _remoteDatabaseContext.Users.FirstOrDefault(u => u.Guid == user.Guid);
            if (existingUser == null) throw new UserNotFoundException(user.Guid);

            existingUser.FIO = user.FIO;
            existingUser.GroupID = user.GroupID;
            _remoteDatabaseContext.SaveChanges(); 

            // Возвращаем обновленный объект UserLocalEnity
            return new UserLocalEnity
            {
                Guid = existingUser.Guid,
                FIO = existingUser.FIO,
                GroupID = existingUser.GroupID
            };
        }

        // Дополнительный метод для DAO, если требуется
        public IEnumerable<RemoteData.RemoteDataBase.DAO.UserDao> GetAllUsersDao => _remoteDatabaseContext.Users.ToList();

        public List<UserDao> GetUserNames()
        {
            return _remoteDatabaseContext.Users
                .Select(u => new UserDao { Guid = u.Guid, FIO = u.FIO })
                .ToList();
        }

    }
}
