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

namespace Indotalent.Features.Purchase.PurchaseRequisition.Cqrs;

public class GetPurchaseRequisitionListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? RequisitionDate { get; set; }
    public string? VendorName { get; set; }
    public decimal? AfterTaxAmount { get; set; }
    public Data.Enums.PurchaseRequisitionStatus RequisitionStatus { get; set; }
}

public record GetPurchaseRequisitionListQuery() : IRequest<List<GetPurchaseRequisitionListResponse>>;

public class GetPurchaseRequisitionListHandler : IRequestHandler<GetPurchaseRequisitionListQuery, List<GetPurchaseRequisitionListResponse>>
{
    private readonly AppDbContext _context;
    public GetPurchaseRequisitionListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetPurchaseRequisitionListResponse>> Handle(GetPurchaseRequisitionListQuery request, CancellationToken cancellationToken)
    {
        return await _context.PurchaseRequisition
            .AsNoTracking()
            .Include(x => x.Vendor)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetPurchaseRequisitionListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                RequisitionDate = x.RequisitionDate,
                VendorName = x.Vendor!.Name,
                AfterTaxAmount = x.AfterTaxAmount,
                RequisitionStatus = x.RequisitionStatus
            }).ToListAsync(cancellationToken);
    }
}