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

namespace Indotalent.Features.Purchase.PurchaseOrder.Cqrs;

public class GetPurchaseOrderListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? OrderDate { get; set; }
    public string? VendorName { get; set; }
    public decimal? AfterTaxAmount { get; set; }
    public Data.Enums.PurchaseOrderStatus OrderStatus { get; set; }
}

public record GetPurchaseOrderListQuery() : IRequest<List<GetPurchaseOrderListResponse>>;

public class GetPurchaseOrderListHandler : IRequestHandler<GetPurchaseOrderListQuery, List<GetPurchaseOrderListResponse>>
{
    private readonly AppDbContext _context;
    public GetPurchaseOrderListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetPurchaseOrderListResponse>> Handle(GetPurchaseOrderListQuery request, CancellationToken cancellationToken)
    {
        return await _context.PurchaseOrder
            .AsNoTracking()
            .Include(x => x.Vendor)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetPurchaseOrderListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                OrderDate = x.OrderDate,
                VendorName = x.Vendor!.Name,
                AfterTaxAmount = x.AfterTaxAmount,
                OrderStatus = x.OrderStatus
            }).ToListAsync(cancellationToken);
    }
}