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

namespace Indotalent.Features.Purchase.Bill.Cqrs;

public record GetPurchaseOrderDetailForBillQuery(string PurchaseOrderId) : IRequest<GetBillByIdResponse?>;

public class GetPurchaseOrderDetailForBillHandler : IRequestHandler<GetPurchaseOrderDetailForBillQuery, GetBillByIdResponse?>
{
    private readonly AppDbContext _context;
    public GetPurchaseOrderDetailForBillHandler(AppDbContext context) => _context = context;

    public async Task<GetBillByIdResponse?> Handle(GetPurchaseOrderDetailForBillQuery request, CancellationToken cancellationToken)
    {
        return await _context.PurchaseOrder
            .AsNoTracking()
            .Include(x => x.PurchaseOrderItemList)
                .ThenInclude(i => i.Product)
            .Where(x => x.Id == request.PurchaseOrderId)
            .Select(x => new GetBillByIdResponse
            {
                PurchaseOrderId = x.Id,
                BeforeTaxAmount = x.BeforeTaxAmount,
                TaxAmount = x.TaxAmount,
                AfterTaxAmount = x.AfterTaxAmount,
                Items = x.PurchaseOrderItemList.Select(i => new BillPurchaseOrderItemResponse
                {
                    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);
    }
}