using CMSMicroservice.Application.Common.Interfaces;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.UserCQ.Commands.VerifyOtpToken;
public class VerifyOtpTokenCommandHandler : IRequestHandler<VerifyOtpTokenCommand, VerifyOtpTokenResponseDto>
{
    private readonly IApplicationDbContext _context;

    public VerifyOtpTokenCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<VerifyOtpTokenResponseDto> Handle(VerifyOtpTokenCommand request, CancellationToken cancellationToken)
    {
        var otpToken = await _context.OtpTokens
            .Where(x => x.Mobile == request.Mobile && x.Purpose == request.Purpose && !x.IsUsed)
            .OrderByDescending(x => x.Id) // Use Id instead of CreatedAt for now
            .FirstOrDefaultAsync(cancellationToken);

        if (otpToken == null || !otpToken.IsValid(request.Code))
            return new VerifyOtpTokenResponseDto { IsSuccess = false, Message = "کد تایید نامعتبر است" };

        var user = await _context.Users
            .Where(x => x.Mobile == request.Mobile)
            .FirstOrDefaultAsync(cancellationToken);

        if (user == null)
            return new VerifyOtpTokenResponseDto { IsSuccess = false, Message = "کاربر یافت نشد" };

        // Mark OTP as used
        otpToken.IsUsed = true;
        await _context.SaveChangesAsync(cancellationToken);

        // TODO: Implement JWT token generation
        return new VerifyOtpTokenResponseDto 
        { 
            IsSuccess = true, 
            Message = "کد تایید با موفقیت تایید شد",
            Token = "TODO_IMPLEMENT_JWT_GENERATION"
        };
    }
}
