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

namespace Indotalent.Features.Purchase.PaymentDisburse.Cqrs;

public class GetPaymentDisburseListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? PaymentDate { get; set; }
    public string? BillNumber { get; set; }
    public string? VendorName { get; set; }
    public decimal PaymentAmount { get; set; }
    public Data.Enums.PaymentDisburseStatus Status { get; set; }
}

public record GetPaymentDisburseListQuery() : IRequest<List<GetPaymentDisburseListResponse>>;

public class GetPaymentDisburseListHandler : IRequestHandler<GetPaymentDisburseListQuery, List<GetPaymentDisburseListResponse>>
{
    private readonly AppDbContext _context;
    public GetPaymentDisburseListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetPaymentDisburseListResponse>> Handle(GetPaymentDisburseListQuery request, CancellationToken cancellationToken)
    {
        return await _context.PaymentDisburse
            .AsNoTracking()
            .Include(x => x.Bill)
                .ThenInclude(b => b!.PurchaseOrder)
                    .ThenInclude(po => po!.Vendor)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetPaymentDisburseListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                PaymentDate = x.PaymentDate,
                BillNumber = x.Bill!.AutoNumber,
                VendorName = x.Bill!.PurchaseOrder!.Vendor!.Name,
                PaymentAmount = x.PaymentAmount ?? 0,
                Status = x.Status
            }).ToListAsync(cancellationToken);
    }
}