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

namespace Indotalent.Features.Sales.PaymentReceive.Cqrs;

public class PaymentReceiveLookupResponse
{
    public List<LookupItem> Invoices { get; set; } = new();
    public List<LookupItem> PaymentMethods { 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 GetPaymentReceiveLookupQuery() : IRequest<PaymentReceiveLookupResponse>;

public class GetPaymentReceiveLookupHandler : IRequestHandler<GetPaymentReceiveLookupQuery, PaymentReceiveLookupResponse>
{
    private readonly AppDbContext _context;
    public GetPaymentReceiveLookupHandler(AppDbContext context) => _context = context;

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

        response.Invoices = await _context.Invoice.AsNoTracking()
            .Where(x => x.InvoiceStatus == InvoiceStatus.Confirmed)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new LookupItem { Id = x.Id, Name = x.AutoNumber })
            .ToListAsync(cancellationToken);

        response.PaymentMethods = await _context.PaymentMethod.AsNoTracking()
            .OrderBy(x => x.Name)
            .Select(x => new LookupItem { Id = x.Id, Name = x.Name })
            .ToListAsync(cancellationToken);

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

        return response;
    }
}