using Indotalent.Data.Entities;
using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Multitenant.TenantUser.Cqrs;

public class GetTenantUserListResponse
{
    public string? Id { get; set; }
    public string? UserId { get; set; }
    public string? FullName { get; set; }
    public string? Email { get; set; }
    public string? Summary { get; set; }
    public bool IsActive { get; set; }
    public string? TenantName { get; set; }
    public string? TenantId { get; set; }
}

public record GetTenantUserListQuery() : IRequest<List<GetTenantUserListResponse>>;

public class GetTenantUserListHandler : IRequestHandler<GetTenantUserListQuery, List<GetTenantUserListResponse>>
{
    private readonly AppDbContext _context;
    private readonly UserManager<ApplicationUser> _userManager;

    public GetTenantUserListHandler(AppDbContext context, UserManager<ApplicationUser> userManager)
    {
        _context = context;
        _userManager = userManager;
    }

    public async Task<List<GetTenantUserListResponse>> Handle(GetTenantUserListQuery request, CancellationToken cancellationToken)
    {
        var tenantUsers = await _context.TenantUser
            .AsNoTracking()
            .Include(x => x.Tenant)
            .OrderBy(x => x.Summary)
            .Select(x => new GetTenantUserListResponse
            {
                Id = x.Id,
                UserId = x.UserId,
                Summary = x.Summary,
                IsActive = x.IsActive,
                TenantName = x.Tenant != null ? x.Tenant.Name : string.Empty,
                TenantId = x.TenantId
            })
            .ToListAsync(cancellationToken);

        // Populate FullName and Email from ApplicationUser
        foreach (var item in tenantUsers)
        {
            if (!string.IsNullOrEmpty(item.UserId))
            {
                var user = await _userManager.FindByIdAsync(item.UserId);
                if (user != null)
                {
                    item.FullName = user.FullName;
                    item.Email = user.Email;
                }
            }
        }

        return tenantUsers;
    }
}
