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

namespace Indotalent.Features.Purchase.Bill.Cqrs;

public class GetBillListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? BillDate { get; set; }
    public string? PurchaseOrderAutoNumber { get; set; }
    public string? VendorName { get; set; }
    public decimal? AfterTaxAmount { get; set; }
    public Data.Enums.BillStatus BillStatus { get; set; }
}

public record GetBillListQuery() : IRequest<List<GetBillListResponse>>;

public class GetBillListHandler : IRequestHandler<GetBillListQuery, List<GetBillListResponse>>
{
    private readonly AppDbContext _context;
    public GetBillListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetBillListResponse>> Handle(GetBillListQuery request, CancellationToken cancellationToken)
    {
        return await _context.Bill
            .AsNoTracking()
            .Include(x => x.PurchaseOrder)
                .ThenInclude(po => po!.Vendor)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetBillListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                BillDate = x.BillDate,
                PurchaseOrderAutoNumber = x.PurchaseOrder!.AutoNumber,
                VendorName = x.PurchaseOrder!.Vendor!.Name,
                AfterTaxAmount = x.PurchaseOrder!.AfterTaxAmount,
                BillStatus = x.BillStatus
            }).ToListAsync(cancellationToken);
    }
}