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

namespace Indotalent.Features.Purchase.PurchaseRequisition.Cqrs;

public class PurchaseRequisitionLookupResponse
{
    public List<LookupItem> Vendors { get; set; } = new();
    public List<LookupItem> Taxes { get; set; } = new();
    public List<LookupItem> Products { 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 GetPurchaseRequisitionLookupQuery() : IRequest<PurchaseRequisitionLookupResponse>;

public class GetPurchaseRequisitionLookupHandler : IRequestHandler<GetPurchaseRequisitionLookupQuery, PurchaseRequisitionLookupResponse>
{
    private readonly AppDbContext _context;
    public GetPurchaseRequisitionLookupHandler(AppDbContext context) => _context = context;

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

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

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

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

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

        return response;
    }
}