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

namespace Indotalent.Features.Purchase.PurchaseReturn.Cqrs;

public class GetPurchaseReturnListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? ReturnDate { get; set; }
    public string? GoodsReceiveNumber { get; set; }
    public Data.Enums.PurchaseReturnStatus Status { get; set; }
}

public record GetPurchaseReturnListQuery() : IRequest<List<GetPurchaseReturnListResponse>>;

public class GetPurchaseReturnListHandler : IRequestHandler<GetPurchaseReturnListQuery, List<GetPurchaseReturnListResponse>>
{
    private readonly AppDbContext _context;
    public GetPurchaseReturnListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetPurchaseReturnListResponse>> Handle(GetPurchaseReturnListQuery request, CancellationToken cancellationToken)
    {
        return await _context.PurchaseReturn
            .AsNoTracking()
            .Include(x => x.GoodsReceive)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetPurchaseReturnListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                ReturnDate = x.ReturnDate,
                GoodsReceiveNumber = x.GoodsReceive!.AutoNumber,
                Status = x.Status
            }).ToListAsync(cancellationToken);
    }
}