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

namespace Indotalent.Features.Sales.SalesQuotation.Cqrs;

public class GetSalesQuotationListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? QuotationDate { get; set; }
    public string? CustomerName { get; set; }
    public decimal? AfterTaxAmount { get; set; }
    public Data.Enums.SalesQuotationStatus QuotationStatus { get; set; }
}

public record GetSalesQuotationListQuery() : IRequest<List<GetSalesQuotationListResponse>>;

public class GetSalesQuotationListHandler : IRequestHandler<GetSalesQuotationListQuery, List<GetSalesQuotationListResponse>>
{
    private readonly AppDbContext _context;
    public GetSalesQuotationListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetSalesQuotationListResponse>> Handle(GetSalesQuotationListQuery request, CancellationToken cancellationToken)
    {
        return await _context.SalesQuotation
            .AsNoTracking()
            .Include(x => x.Customer)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetSalesQuotationListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                QuotationDate = x.QuotationDate,
                CustomerName = x.Customer!.Name,
                AfterTaxAmount = x.AfterTaxAmount,
                QuotationStatus = x.QuotationStatus
            }).ToListAsync(cancellationToken);
    }
}