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

namespace Indotalent.Features.Purchase.PurchaseReport.Cqrs;

public record GetPurchaseReportListDto
{
    public string? Id { get; init; }
    public string? PurchaseOrderId { get; init; }
    public string? PurchaseOrderNumber { get; init; }
    public string? VendorName { get; init; }
    public string? ProductId { get; init; }
    public string? ProductName { get; init; }
    public string? ProductNumber { get; init; }
    public string? Summary { get; init; }
    public decimal? UnitPrice { get; init; }
    public double? Quantity { get; init; }
    public decimal? Total { get; init; }
    public DateTime? OrderDate { get; init; }
}

public record GetPurchaseReportListQuery() : IRequest<List<GetPurchaseReportListDto>>;

public class GetPurchaseReportListHandler : IRequestHandler<GetPurchaseReportListQuery, List<GetPurchaseReportListDto>>
{
    private readonly AppDbContext _context;

    public GetPurchaseReportListHandler(AppDbContext context)
    {
        _context = context;
    }

    public async Task<List<GetPurchaseReportListDto>> Handle(GetPurchaseReportListQuery request, CancellationToken cancellationToken)
    {
        var results = await _context.PurchaseOrderItem
            .AsNoTracking()
            .Include(x => x.PurchaseOrder)
                .ThenInclude(x => x!.Vendor)
            .Include(x => x.Product)
            .OrderByDescending(x => x.PurchaseOrder!.OrderDate)
            .Select(x => new GetPurchaseReportListDto
            {
                Id = x.Id,
                PurchaseOrderId = x.PurchaseOrderId,
                PurchaseOrderNumber = x.PurchaseOrder != null ? x.PurchaseOrder.AutoNumber : string.Empty,
                VendorName = (x.PurchaseOrder != null && x.PurchaseOrder.Vendor != null) ? x.PurchaseOrder.Vendor.Name : string.Empty,
                ProductId = x.ProductId,
                ProductName = x.Product != null ? x.Product.Name : string.Empty,
                ProductNumber = x.Product != null ? x.Product.AutoNumber : string.Empty,
                Summary = x.Summary,
                UnitPrice = x.UnitPrice,
                Quantity = x.Quantity,
                Total = x.Total,
                OrderDate = x.PurchaseOrder != null ? x.PurchaseOrder.OrderDate : null
            })
            .ToListAsync(cancellationToken);

        return results;
    }
}