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

namespace Indotalent.Features.Multitenant.TenantUser.Cqrs;

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

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

public record LookupTenantUserQuery() : IRequest<LookupTenantUserResponse>;

public class LookupTenantUserHandler : IRequestHandler<LookupTenantUserQuery, LookupTenantUserResponse>
{
    private readonly AppDbContext _context;

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

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

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

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

        return result;
    }
}