using MediatR;
using MiningService.Domain.AggregatesModel.MinerAggregate;
using MiningService.Domain.Exceptions;

namespace MiningService.API.Application.Commands;

/// <summary>
/// EN: Handler for StartMiningCommand.
/// VI: Handler cho StartMiningCommand.
/// </summary>
public class StartMiningCommandHandler : IRequestHandler<StartMiningCommand, StartMiningResult>
{
    private readonly IMinerRepository _minerRepository;

    public StartMiningCommandHandler(IMinerRepository minerRepository)
    {
        _minerRepository = minerRepository;
    }

    public async Task<StartMiningResult> Handle(StartMiningCommand request, CancellationToken cancellationToken)
    {
        var miner = await _minerRepository.GetByUserIdAsync(request.UserId, cancellationToken)
            ?? throw new MinerNotFoundException($"Miner with UserId {request.UserId} not found");

        var session = miner.StartMiningSession();

        _minerRepository.Update(miner);
        await _minerRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        return new StartMiningResult(
            session.SessionId,
            session.HourlyRate,
            session.EndTime,
            miner.Streak.CurrentStreak);
    }
}
