using FluentResults;
using NexusReader.Application.Abstractions.Messaging;
using NexusReader.Application.Abstractions.Persistence;
using NexusReader.Domain.Entities;

namespace NexusReader.Application.Commands.Quiz;

public sealed class SubmitQuizResultCommandHandler : ICommandHandler<SubmitQuizResultCommand>
{
    private readonly IQuizResultRepository _quizResultRepository;

    public SubmitQuizResultCommandHandler(IQuizResultRepository quizResultRepository)
    {
        _quizResultRepository = quizResultRepository;
    }

    public async Task<Result> Handle(SubmitQuizResultCommand request, CancellationToken cancellationToken)
    {
        var user = await _quizResultRepository.FindUserByIdAsync(request.UserId, cancellationToken);
        if (user == null)
        {
            return Result.Fail("User not found.");
        }

        var quizResult = new QuizResult
        {
            Id = Guid.NewGuid(),
            UserId = request.UserId,
            TenantId = string.IsNullOrEmpty(user.TenantId) ? "global" : user.TenantId,
            Topic = request.Topic,
            Score = request.Score,
            TotalQuestions = request.TotalQuestions,
            CompletedDate = DateTime.UtcNow
        };

        _quizResultRepository.AddQuizResult(quizResult);
        await _quizResultRepository.SaveChangesAsync(cancellationToken);

        return Result.Ok();
    }
}
