using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Inventory.Product.Cqrs;

public class LookupProductResponse
{
    public List<LookupItem> UnitMeasures { get; set; } = new();
    public List<LookupItem> ProductGroups { get; set; } = new();
}

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

public record LookupProductQuery() : IRequest<LookupProductResponse>;

public class LookupProductHandler : IRequestHandler<LookupProductQuery, LookupProductResponse>
{
    private readonly AppDbContext _context;

    public LookupProductHandler(AppDbContext context) => _context = context;

    public async Task<LookupProductResponse> Handle(LookupProductQuery request, CancellationToken cancellationToken)
    {
        var result = new LookupProductResponse();

        result.UnitMeasures = await _context.UnitMeasure
            .AsNoTracking()
            .OrderBy(x => x.Name)
            .Select(x => new LookupItem { Id = x.Id, Name = x.Name })
            .ToListAsync(cancellationToken);

        result.ProductGroups = await _context.ProductGroup
            .AsNoTracking()
            .OrderBy(x => x.Name)
            .Select(x => new LookupItem { Id = x.Id, Name = x.Name })
            .ToListAsync(cancellationToken);

        return result;
    }
}