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

namespace Indotalent.Features.Sales.PaymentReceive.Cqrs;

public record GetInvoiceDetailForPaymentQuery(string InvoiceId) : IRequest<GetPaymentReceiveByIdResponse?>;

public class GetInvoiceDetailForPaymentHandler : IRequestHandler<GetInvoiceDetailForPaymentQuery, GetPaymentReceiveByIdResponse?>
{
    private readonly AppDbContext _context;
    public GetInvoiceDetailForPaymentHandler(AppDbContext context) => _context = context;

    public async Task<GetPaymentReceiveByIdResponse?> Handle(GetInvoiceDetailForPaymentQuery request, CancellationToken cancellationToken)
    {
        var invoice = await _context.Invoice
            .AsNoTracking()
            .Include(x => x.SalesOrder)
                .ThenInclude(so => so!.Customer)
            .Include(x => x.SalesOrder)
                .ThenInclude(so => so!.SalesOrderItemList)
                    .ThenInclude(si => si.Product)
            .FirstOrDefaultAsync(x => x.Id == request.InvoiceId, cancellationToken);

        if (invoice == null) return null;

        var salesOrder = invoice.SalesOrder;

        return new GetPaymentReceiveByIdResponse
        {
            InvoiceId = invoice.Id,
            InvoiceNumber = invoice.AutoNumber,
            CustomerName = salesOrder?.Customer?.Name,
            CustomerStreet = salesOrder?.Customer?.Street,
            CustomerCity = salesOrder?.Customer?.City,
            SalesOrderBeforeTaxAmount = salesOrder?.BeforeTaxAmount ?? 0,
            SalesOrderTaxAmount = salesOrder?.TaxAmount ?? 0,
            SalesOrderAfterTaxAmount = salesOrder?.AfterTaxAmount ?? 0,
            PaymentAmount = salesOrder?.AfterTaxAmount ?? 0,
            Items = salesOrder?.SalesOrderItemList.Select(x => new PaymentReceiveItemResponse
            {
                Id = x.Id,
                ProductId = x.ProductId,
                ProductName = x.Product?.Name,
                Summary = x.Summary,
                UnitPrice = x.UnitPrice ?? 0,
                Quantity = x.Quantity ?? 0,
                Total = x.Total ?? 0
            }).ToList() ?? new()
        };
    }
}