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

namespace Indotalent.Features.Purchase.GoodsReceive.Cqrs;

public class GetGoodsReceiveListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? ReceiveDate { get; set; }
    public string? PurchaseOrderNumber { get; set; }
    public Data.Enums.GoodsReceiveStatus Status { get; set; }
}

public record GetGoodsReceiveListQuery() : IRequest<List<GetGoodsReceiveListResponse>>;

public class GetGoodsReceiveListHandler : IRequestHandler<GetGoodsReceiveListQuery, List<GetGoodsReceiveListResponse>>
{
    private readonly AppDbContext _context;
    public GetGoodsReceiveListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetGoodsReceiveListResponse>> Handle(GetGoodsReceiveListQuery request, CancellationToken cancellationToken)
    {
        return await _context.GoodsReceive
            .AsNoTracking()
            .Include(x => x.PurchaseOrder)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetGoodsReceiveListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                ReceiveDate = x.ReceiveDate,
                PurchaseOrderNumber = x.PurchaseOrder!.AutoNumber,
                Status = x.Status
            }).ToListAsync(cancellationToken);
    }
}