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

namespace Indotalent.Features.Sales.Invoice.Cqrs;

public record GetSalesOrderDetailForInvoiceQuery(string SalesOrderId) : IRequest<GetInvoiceByIdResponse?>;

public class GetSalesOrderDetailForInvoiceHandler : IRequestHandler<GetSalesOrderDetailForInvoiceQuery, GetInvoiceByIdResponse?>
{
    private readonly AppDbContext _context;
    public GetSalesOrderDetailForInvoiceHandler(AppDbContext context) => _context = context;

    public async Task<GetInvoiceByIdResponse?> Handle(GetSalesOrderDetailForInvoiceQuery request, CancellationToken cancellationToken)
    {
        return await _context.SalesOrder
            .AsNoTracking()
            .Include(x => x.SalesOrderItemList)
                .ThenInclude(x => x.Product)
            .Where(x => x.Id == request.SalesOrderId)
            .Select(x => new GetInvoiceByIdResponse
            {
                SalesOrderId = x.Id,
                BeforeTaxAmount = x.BeforeTaxAmount,
                TaxAmount = x.TaxAmount,
                AfterTaxAmount = x.AfterTaxAmount,
                Items = x.SalesOrderItemList.Select(i => new InvoiceSalesOrderItemResponse
                {
                    Id = i.Id,
                    ProductId = i.ProductId,
                    ProductName = i.Product!.Name,
                    Summary = i.Summary,
                    UnitPrice = i.UnitPrice,
                    Quantity = i.Quantity,
                    Total = i.Total
                }).ToList()
            }).FirstOrDefaultAsync(cancellationToken);
    }
}