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

namespace Indotalent.Features.Thirdparty.CustomerContact.Cqrs;

public class LookupCustomerContactResponse
{
    public List<LookupItem> Customers { get; set; } = new();
}

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

public record LookupCustomerContactQuery() : IRequest<LookupCustomerContactResponse>;

public class LookupCustomerContactHandler : IRequestHandler<LookupCustomerContactQuery, LookupCustomerContactResponse>
{
    private readonly AppDbContext _context;

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

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

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

        return result;
    }
}