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

namespace Indotalent.Features.Sales.DeliveryOrder.Cqrs;

public class GetDeliveryOrderListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? DeliveryDate { get; set; }
    public string? SalesOrderNumber { get; set; }
    public Data.Enums.DeliveryOrderStatus Status { get; set; }
}

public record GetDeliveryOrderListQuery() : IRequest<List<GetDeliveryOrderListResponse>>;

public class GetDeliveryOrderListHandler : IRequestHandler<GetDeliveryOrderListQuery, List<GetDeliveryOrderListResponse>>
{
    private readonly AppDbContext _context;
    public GetDeliveryOrderListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetDeliveryOrderListResponse>> Handle(GetDeliveryOrderListQuery request, CancellationToken cancellationToken)
    {
        return await _context.DeliveryOrder
            .AsNoTracking()
            .Include(x => x.SalesOrder)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetDeliveryOrderListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                DeliveryDate = x.DeliveryDate,
                SalesOrderNumber = x.SalesOrder!.AutoNumber,
                Status = x.Status
            }).ToListAsync(cancellationToken);
    }
}