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

namespace Indotalent.Features.Sales.InvoiceReport.Cqrs;

public record GetInvoiceReportListDto
{
    public string? Id { get; init; }
    public string? Number { get; init; }
    public DateTime? InvoiceDate { get; init; }
    public string? StatusName { get; init; }
    public string? SalesOrderNumber { get; init; }
    public decimal? AfterTaxAmount { get; init; }
    public string? CustomerName { get; init; }
}

public record GetInvoiceReportListQuery() : IRequest<List<GetInvoiceReportListDto>>;

public class GetInvoiceReportListHandler : IRequestHandler<GetInvoiceReportListQuery, List<GetInvoiceReportListDto>>
{
    private readonly AppDbContext _context;

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

    public async Task<List<GetInvoiceReportListDto>> Handle(GetInvoiceReportListQuery request, CancellationToken cancellationToken)
    {
        var results = await _context.Invoice
            .AsNoTracking()
            .Include(x => x.SalesOrder)
                .ThenInclude(x => x!.Customer)
            .OrderByDescending(x => x.InvoiceDate)
            .Select(x => new GetInvoiceReportListDto
            {
                Id = x.Id,
                Number = x.AutoNumber,
                InvoiceDate = x.InvoiceDate,
                StatusName = x.InvoiceStatus.GetDescription(),
                SalesOrderNumber = x.SalesOrder != null ? x.SalesOrder.AutoNumber : string.Empty,
                AfterTaxAmount = x.SalesOrder != null ? x.SalesOrder.AfterTaxAmount : 0,
                CustomerName = (x.SalesOrder != null && x.SalesOrder.Customer != null) ? x.SalesOrder.Customer.Name : string.Empty
            })
            .ToListAsync(cancellationToken);

        return results;
    }
}