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

namespace Indotalent.Features.Sales.Invoice.Cqrs;

public class InvoiceLookupResponse
{
    public List<LookupItem> SalesOrders { get; set; } = new();
    public List<LookupStatusItem> Statuses { get; set; } = new();
}

public class LookupItem
{
    public string? Id { get; set; }
    public string? Name { get; set; }
}

public class LookupStatusItem
{
    public int Value { get; set; }
    public string? Name { get; set; }
}

public record GetInvoiceLookupQuery() : IRequest<InvoiceLookupResponse>;

public class GetInvoiceLookupHandler : IRequestHandler<GetInvoiceLookupQuery, InvoiceLookupResponse>
{
    private readonly AppDbContext _context;
    public GetInvoiceLookupHandler(AppDbContext context) => _context = context;

    public async Task<InvoiceLookupResponse> Handle(GetInvoiceLookupQuery request, CancellationToken cancellationToken)
    {
        var response = new InvoiceLookupResponse();

        response.SalesOrders = await _context.SalesOrder.AsNoTracking()
            .Where(x => x.OrderStatus == SalesOrderStatus.Confirmed)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new LookupItem { Id = x.Id, Name = x.AutoNumber })
            .ToListAsync(cancellationToken);

        response.Statuses = Enum.GetValues(typeof(InvoiceStatus))
            .Cast<InvoiceStatus>()
            .Select(x => new LookupStatusItem
            {
                Value = (int)x,
                Name = x.GetDescription()
            }).ToList();

        return response;
    }
}