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

namespace Indotalent.Features.Thirdparty.Customer.Cqrs;

public class LookupCustomerResponse
{
    public List<LookupItem> CustomerGroups { get; set; } = new();
    public List<LookupItem> CustomerCategories { get; set; } = new();
}

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

public record LookupCustomerQuery() : IRequest<LookupCustomerResponse>;

public class LookupCustomerHandler : IRequestHandler<LookupCustomerQuery, LookupCustomerResponse>
{
    private readonly AppDbContext _context;

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

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

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

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

        return result;
    }
}