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

namespace Indotalent.Features.Sales.SalesOrder.Cqrs;

public class GetSalesOrderListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? OrderDate { get; set; }
    public string? CustomerName { get; set; }
    public decimal? AfterTaxAmount { get; set; }
    public Data.Enums.SalesOrderStatus OrderStatus { get; set; }
}

public record GetSalesOrderListQuery() : IRequest<List<GetSalesOrderListResponse>>;

public class GetSalesOrderListHandler : IRequestHandler<GetSalesOrderListQuery, List<GetSalesOrderListResponse>>
{
    private readonly AppDbContext _context;
    public GetSalesOrderListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetSalesOrderListResponse>> Handle(GetSalesOrderListQuery request, CancellationToken cancellationToken)
    {
        return await _context.SalesOrder
            .AsNoTracking()
            .Include(x => x.Customer)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetSalesOrderListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                OrderDate = x.OrderDate,
                CustomerName = x.Customer!.Name,
                AfterTaxAmount = x.AfterTaxAmount,
                OrderStatus = x.OrderStatus
            }).ToListAsync(cancellationToken);
    }
}