using AutoMapper;
using UserManagement.Data;
using UserManagement.Data.Dto;
using UserManagement.MediatR.Commands;
using MediatR;
using Microsoft.AspNetCore.Identity;
using System.Threading;
using System.Threading.Tasks;
using System;
using UserManagement.Helper;
using Microsoft.Extensions.Logging;
using UserManagement.Repository;
using Microsoft.EntityFrameworkCore;
using UserManagement.Common.UnitOfWork;
using UserManagement.Domain;

namespace UserManagement.MediatR.Handlers
{
    public class DeleteUserCommandHandler(
        IUserRepository userRepository,
        IMapper mapper,
        UserInfoToken userInfoToken,
        ILogger<DeleteUserCommandHandler> logger,
        IUnitOfWork<UserContext> _uow
        ) : IRequestHandler<DeleteUserCommand, ServiceResponse<UserDto>>
    {
        public async Task<ServiceResponse<UserDto>> Handle(DeleteUserCommand request, CancellationToken cancellationToken)
        {
            var appUser = await userRepository.All.IgnoreQueryFilters().FirstOrDefaultAsync(c => c.Id == request.Id);
            if (appUser == null)
            {
                logger.LogError("User does not exist.");
                return ServiceResponse<UserDto>.Return409("User does not exist.");
            }

            appUser.IsActive = !appUser.IsActive;
            if (!appUser.IsActive)
            {
                appUser.DeletedDate = DateTime.Now.ToLocalTime();
                appUser.DeletedBy = Guid.Parse(userInfoToken.Id);
            }
            else
            {
                appUser.DeletedDate = null;
                appUser.DeletedBy = null;
            }
            userRepository.Update(appUser);
            if (await _uow.SaveAsync() <= 0)
            {
                return ServiceResponse<UserDto>.Return500();
            }
            return ServiceResponse<UserDto>.ReturnResultWith200(mapper.Map<UserDto>(appUser));
        }
    }
}
