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

namespace Indotalent.Features.Sales.Invoice.Cqrs;

public class GetInvoiceListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? InvoiceDate { get; set; }
    public string? SalesOrderAutoNumber { get; set; }
    public string? CustomerName { get; set; }
    public decimal? AfterTaxAmount { get; set; }
    public Data.Enums.InvoiceStatus InvoiceStatus { get; set; }
}

public record GetInvoiceListQuery() : IRequest<List<GetInvoiceListResponse>>;

public class GetInvoiceListHandler : IRequestHandler<GetInvoiceListQuery, List<GetInvoiceListResponse>>
{
    private readonly AppDbContext _context;
    public GetInvoiceListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetInvoiceListResponse>> Handle(GetInvoiceListQuery request, CancellationToken cancellationToken)
    {
        return await _context.Invoice
            .AsNoTracking()
            .Include(x => x.SalesOrder)
                .ThenInclude(so => so!.Customer)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetInvoiceListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                InvoiceDate = x.InvoiceDate,
                SalesOrderAutoNumber = x.SalesOrder!.AutoNumber,
                CustomerName = x.SalesOrder!.Customer!.Name,
                AfterTaxAmount = x.SalesOrder!.AfterTaxAmount,
                InvoiceStatus = x.InvoiceStatus
            }).ToListAsync(cancellationToken);
    }
}