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

namespace Indotalent.Features.Inventory.TransferIn.Cqrs;

public class GetTransferInListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? TransferReceiveDate { get; set; }
    public string? TransferOutNumber { get; set; }
    public string? WarehouseToName { get; set; }
    public Data.Enums.TransferStatus Status { get; set; }
}

public record GetTransferInListQuery() : IRequest<List<GetTransferInListResponse>>;

public class GetTransferInListHandler : IRequestHandler<GetTransferInListQuery, List<GetTransferInListResponse>>
{
    private readonly AppDbContext _context;
    public GetTransferInListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetTransferInListResponse>> Handle(GetTransferInListQuery request, CancellationToken cancellationToken)
    {
        return await _context.TransferIn
            .AsNoTracking()
            .Include(x => x.TransferOut)
            .ThenInclude(x => x!.WarehouseTo)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetTransferInListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                TransferReceiveDate = x.TransferReceiveDate,
                TransferOutNumber = x.TransferOut!.AutoNumber,
                WarehouseToName = x.TransferOut!.WarehouseTo!.Name,
                Status = x.Status
            }).ToListAsync(cancellationToken);
    }
}