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

namespace Indotalent.Features.Purchase.PaymentDisburse.Cqrs;

public class PaymentDisburseLookupResponse
{
    public List<LookupItem> Bills { 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 GetPaymentDisburseLookupQuery() : IRequest<PaymentDisburseLookupResponse>;

public class GetPaymentDisburseLookupHandler : IRequestHandler<GetPaymentDisburseLookupQuery, PaymentDisburseLookupResponse>
{
    private readonly AppDbContext _context;
    public GetPaymentDisburseLookupHandler(AppDbContext context) => _context = context;

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

        response.Bills = await _context.Bill.AsNoTracking()
            .Where(x => x.BillStatus == BillStatus.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(PaymentDisburseStatus))
            .Cast<PaymentDisburseStatus>()
            .Select(x => new LookupStatusItem
            {
                Value = (int)x,
                Name = x.GetDescription()
            }).ToList();

        return response;
    }
}