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

namespace Indotalent.Features.Sales.SalesReturn.Cqrs;

public class GetSalesReturnListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? ReturnDate { get; set; }
    public string? DeliveryOrderNumber { get; set; }
    public Data.Enums.SalesReturnStatus Status { get; set; }
}

public record GetSalesReturnListQuery() : IRequest<List<GetSalesReturnListResponse>>;

public class GetSalesReturnListHandler : IRequestHandler<GetSalesReturnListQuery, List<GetSalesReturnListResponse>>
{
    private readonly AppDbContext _context;
    public GetSalesReturnListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetSalesReturnListResponse>> Handle(GetSalesReturnListQuery request, CancellationToken cancellationToken)
    {
        return await _context.SalesReturn
            .AsNoTracking()
            .Include(x => x.DeliveryOrder)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetSalesReturnListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                ReturnDate = x.ReturnDate,
                DeliveryOrderNumber = x.DeliveryOrder!.AutoNumber,
                Status = x.Status
            }).ToListAsync(cancellationToken);
    }
}