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

namespace Indotalent.Features.Sales.PaymentReceive.Cqrs;

public class GetPaymentReceiveListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? PaymentDate { get; set; }
    public string? InvoiceNumber { get; set; }
    public string? CustomerName { get; set; }
    public decimal PaymentAmount { get; set; }
    public Data.Enums.PaymentReceiveStatus Status { get; set; }
}

public record GetPaymentReceiveListQuery() : IRequest<List<GetPaymentReceiveListResponse>>;

public class GetPaymentReceiveListHandler : IRequestHandler<GetPaymentReceiveListQuery, List<GetPaymentReceiveListResponse>>
{
    private readonly AppDbContext _context;
    public GetPaymentReceiveListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetPaymentReceiveListResponse>> Handle(GetPaymentReceiveListQuery request, CancellationToken cancellationToken)
    {
        return await _context.PaymentReceive
            .AsNoTracking()
            .Include(x => x.Invoice)
                .ThenInclude(i => i!.SalesOrder)
                    .ThenInclude(so => so!.Customer)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetPaymentReceiveListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                PaymentDate = x.PaymentDate,
                InvoiceNumber = x.Invoice!.AutoNumber,
                CustomerName = x.Invoice!.SalesOrder!.Customer!.Name,
                PaymentAmount = x.PaymentAmount ?? 0,
                Status = x.Status
            }).ToListAsync(cancellationToken);
    }
}