using Indotalent.Features.Sales.SalesReturn.Cqrs;
using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Inventory.TransferOut.Cqrs;

public class GetTransferOutListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? TransferReleaseDate { get; set; }
    public string? WarehouseFromName { get; set; }
    public string? WarehouseToName { get; set; }
    public Data.Enums.TransferStatus Status { get; set; }
}

public record GetTransferOutListQuery() : IRequest<List<GetTransferOutListResponse>>;

public class GetTransferOutListHandler : IRequestHandler<GetTransferOutListQuery, List<GetTransferOutListResponse>>
{
    private readonly AppDbContext _context;
    public GetTransferOutListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetTransferOutListResponse>> Handle(GetTransferOutListQuery request, CancellationToken cancellationToken)
    {
        return await _context.TransferOut
            .AsNoTracking()
            .Include(x => x.WarehouseFrom)
            .Include(x => x.WarehouseTo)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetTransferOutListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                TransferReleaseDate = x.TransferReleaseDate,
                WarehouseFromName = x.WarehouseFrom!.Name,
                WarehouseToName = x.WarehouseTo!.Name,
                Status = x.Status
            }).ToListAsync(cancellationToken);
    }
}