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

namespace Indotalent.Features.Purchase.BillReport.Cqrs;

public record GetBillReportListDto
{
    public string? Id { get; init; }
    public string? Number { get; init; }
    public DateTime? BillDate { get; init; }
    public string? StatusName { get; init; }
    public string? PurchaseOrderNumber { get; init; }
    public decimal? AfterTaxAmount { get; init; }
    public string? VendorName { get; init; }
}

public record GetBillReportListQuery() : IRequest<List<GetBillReportListDto>>;

public class GetBillReportListHandler : IRequestHandler<GetBillReportListQuery, List<GetBillReportListDto>>
{
    private readonly AppDbContext _context;

    public GetBillReportListHandler(AppDbContext context)
    {
        _context = context;
    }

    public async Task<List<GetBillReportListDto>> Handle(GetBillReportListQuery request, CancellationToken cancellationToken)
    {
        var results = await _context.Bill
            .AsNoTracking()
            .Include(x => x.PurchaseOrder)
                .ThenInclude(x => x!.Vendor)
            .OrderByDescending(x => x.BillDate)
            .Select(x => new GetBillReportListDto
            {
                Id = x.Id,
                Number = x.AutoNumber,
                BillDate = x.BillDate,
                StatusName = x.BillStatus.GetDescription(),
                PurchaseOrderNumber = x.PurchaseOrder != null ? x.PurchaseOrder.AutoNumber : string.Empty,
                AfterTaxAmount = x.PurchaseOrder != null ? x.PurchaseOrder.AfterTaxAmount : 0,
                VendorName = (x.PurchaseOrder != null && x.PurchaseOrder.Vendor != null) ? x.PurchaseOrder.Vendor.Name : string.Empty
            })
            .ToListAsync(cancellationToken);

        return results;
    }
}