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

namespace Indotalent.Features.Multitenant.Tenant.Cqrs;

public class LookupTenantResponse
{
    public List<LookupItem> Tenants { get; set; } = new();
}

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

public record LookupTenantQuery() : IRequest<LookupTenantResponse>;

public class LookupTenantHandler : IRequestHandler<LookupTenantQuery, LookupTenantResponse>
{
    private readonly AppDbContext _context;

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

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

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

        return result;
    }
}