using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace CMSMicroservice.Application.OrderVATCQ.Queries.GetOrderVAT;

public class GetOrderVATQueryHandler : IRequestHandler<GetOrderVATQuery, OrderVATDto?>
{
    private readonly IApplicationDbContext _context;
    private readonly ILogger<GetOrderVATQueryHandler> _logger;

    public GetOrderVATQueryHandler(
        IApplicationDbContext context,
        ILogger<GetOrderVATQueryHandler> logger)
    {
        _context = context;
        _logger = logger;
    }

    public async Task<OrderVATDto?> Handle(GetOrderVATQuery request, CancellationToken cancellationToken)
    {
        var orderVAT = await _context.OrderVATs
            .Where(x => x.OrderId == request.OrderId && !x.IsDeleted)
            .Select(x => new OrderVATDto
            {
                Id = x.Id,
                OrderId = x.OrderId,
                VATRate = x.VATRate,
                VATRatePercentage = $"{x.VATRate * 100:F1}%",
                BaseAmount = x.BaseAmount,
                VATAmount = x.VATAmount,
                TotalAmount = x.TotalAmount,
                IsPaid = x.IsPaid,
                PaidAt = x.PaidAt,
                Note = x.Note,
                Created = x.Created
            })
            .FirstOrDefaultAsync(cancellationToken);

        if (orderVAT != null)
        {
            _logger.LogInformation(
                "Retrieved VAT for order {OrderId}. VAT Amount: {VATAmount}",
                request.OrderId,
                orderVAT.VATAmount
            );
        }

        return orderVAT;
    }
}
