using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Purchase.PaymentDisburseReport.Cqrs;

public record GetPaymentDisburseReportListDto
{
    public string? Id { get; init; }
    public string? Number { get; init; }
    public DateTime? PaymentDate { get; init; }
    public string? PaymentMethodName { get; init; }
    public decimal? PaymentAmount { get; init; }
    public string? StatusName { get; init; }
    public string? BillNumber { get; init; }
    public string? VendorName { get; init; }
}

public record GetPaymentDisburseReportListQuery() : IRequest<List<GetPaymentDisburseReportListDto>>;

public class GetPaymentDisburseReportListHandler : IRequestHandler<GetPaymentDisburseReportListQuery, List<GetPaymentDisburseReportListDto>>
{
    private readonly AppDbContext _context;

    public GetPaymentDisburseReportListHandler(AppDbContext context)
    {
        _context = context;
    }

    public async Task<List<GetPaymentDisburseReportListDto>> Handle(GetPaymentDisburseReportListQuery request, CancellationToken cancellationToken)
    {
        var results = await _context.PaymentDisburse
            .AsNoTracking()
            .Include(x => x.PaymentMethod)
            .Include(x => x.Bill)
                .ThenInclude(x => x!.PurchaseOrder)
                    .ThenInclude(x => x!.Vendor)
            .OrderByDescending(x => x.PaymentDate)
            .Select(x => new GetPaymentDisburseReportListDto
            {
                Id = x.Id,
                Number = x.AutoNumber,
                PaymentDate = x.PaymentDate,
                PaymentMethodName = x.PaymentMethod != null ? x.PaymentMethod.Name : string.Empty,
                PaymentAmount = x.PaymentAmount,
                StatusName = x.Status.GetDescription(),
                BillNumber = x.Bill != null ? x.Bill.AutoNumber : string.Empty,
                VendorName = (x.Bill != null && x.Bill.PurchaseOrder != null && x.Bill.PurchaseOrder.Vendor != null)
                                ? x.Bill.PurchaseOrder.Vendor.Name : string.Empty
            })
            .ToListAsync(cancellationToken);

        return results;
    }
}