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

namespace Indotalent.Features.Thirdparty.Vendor.Cqrs;

public class LookupVendorResponse
{
    public List<LookupItem> VendorGroups { get; set; } = new();
    public List<LookupItem> VendorCategories { get; set; } = new();
}

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

public record LookupVendorQuery() : IRequest<LookupVendorResponse>;

public class LookupVendorHandler : IRequestHandler<LookupVendorQuery, LookupVendorResponse>
{
    private readonly AppDbContext _context;

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

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

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

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

        return result;
    }
}