using Knot.Contracts.Auth.Domain;
using Knot.Contracts.Auth.Application.Abstractions;
using Knot.Contracts.Auth.Application.Auth.DTOs;
using Knot.Modules.Admin.Application.Admin.DTOs;
using System;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Knot.Contracts.Admin.Abstractions;

namespace Knot.Modules.Admin.Application.Admin.Commands;

public record ResetUserPasswordCommand(Guid UserId, string NewPassword) : ICommand<SuccessResponse>;

internal sealed class ResetUserPasswordCommandHandler : ICommandHandler<ResetUserPasswordCommand, SuccessResponse>
{
    private readonly IUserRepository _userRepository;
    private readonly IAuthUnitOfWork _identityUnitOfWork;

    public ResetUserPasswordCommandHandler(IUserRepository userRepository, IAuthUnitOfWork identityUnitOfWork)
    {
        _userRepository = userRepository;
        _identityUnitOfWork = identityUnitOfWork;
    }

    public async Task<Result<SuccessResponse>> Handle(ResetUserPasswordCommand request, CancellationToken cancellationToken)
    {
        var user = await _userRepository.GetByIdAsync(request.UserId, cancellationToken);
        if (user == null)
        {
            return Result.Failure<SuccessResponse>(Error.NotFound("Auth.UserNotFound", "User not found"));
        }

        if (string.IsNullOrWhiteSpace(request.NewPassword))
            return Result.Failure<SuccessResponse>(new Error("Admin.InvalidPassword", "Invalid password"));

        var hash = BCrypt.Net.BCrypt.HashPassword(request.NewPassword);
        user.PasswordHash = hash;

        await _userRepository.UpdateAsync(user, cancellationToken);
        await _identityUnitOfWork.SaveChangesAsync(cancellationToken);
        return Result.Success(new SuccessResponse(true));
    }
}

