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

namespace Indotalent.Features.Purchase.Bill.Cqrs;

public class BillLookupResponse
{
    public List<LookupItem> PurchaseOrders { 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 GetBillLookupQuery() : IRequest<BillLookupResponse>;

public class GetBillLookupHandler : IRequestHandler<GetBillLookupQuery, BillLookupResponse>
{
    private readonly AppDbContext _context;
    public GetBillLookupHandler(AppDbContext context) => _context = context;

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

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

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

        return response;
    }
}