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

namespace CMSMicroservice.Application.UserCQ.Commands.AcceptContract;
public class AcceptContractCommandHandler : IRequestHandler<AcceptContractCommand, AcceptContractResponseDto>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUserService;

    public AcceptContractCommandHandler(IApplicationDbContext context, ICurrentUserService currentUserService)
    {
        _context = context;
        _currentUserService = currentUserService;
    }

    public async Task<AcceptContractResponseDto> Handle(AcceptContractCommand request, CancellationToken cancellationToken)
    {
        // Verify OTP first
        var otpToken = await _context.OtpTokens
            .Where(x => x.Mobile == _currentUserService.Username && x.Purpose == "signContract" && !x.IsUsed && x.Code == request.Code)
            .OrderByDescending(x => x.Id) // Use Id instead of CreatedAt for now
            .FirstOrDefaultAsync(cancellationToken);

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

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

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

        // Create user contract
        var userContract = new UserContract
        {
            UserId = user.Id,
            ContractId = 1, // Default contract
            SignGuid = request.SignGuid,
            SignedPdfFile = request.ContractHtml
        };

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

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