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

namespace Indotalent.Features.Sales.SalesReport.Cqrs;

public record GetSalesReportListDto
{
    public string? Id { get; init; }
    public string? SalesOrderId { get; init; }
    public string? SalesOrderNumber { get; init; }
    public string? CustomerName { 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 GetSalesReportListQuery() : IRequest<List<GetSalesReportListDto>>;

public class GetSalesReportListHandler : IRequestHandler<GetSalesReportListQuery, List<GetSalesReportListDto>>
{
    private readonly AppDbContext _context;

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

    public async Task<List<GetSalesReportListDto>> Handle(GetSalesReportListQuery request, CancellationToken cancellationToken)
    {
        var results = await _context.SalesOrderItem
            .AsNoTracking()
            .Include(x => x.SalesOrder)
                .ThenInclude(x => x!.Customer)
            .Include(x => x.Product)
            .OrderByDescending(x => x.SalesOrder!.OrderDate)
            .Select(x => new GetSalesReportListDto
            {
                Id = x.Id,
                SalesOrderId = x.SalesOrderId,
                SalesOrderNumber = x.SalesOrder != null ? x.SalesOrder.AutoNumber : string.Empty,
                CustomerName = x.SalesOrder!.Customer != null ? x.SalesOrder.Customer.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.SalesOrder != null ? x.SalesOrder.OrderDate : null
            })
            .ToListAsync(cancellationToken);

        return results;
    }
}