using System.Text.Json;
using ColaFlow.Modules.Identity.Domain.Aggregates.Tenants;
using ColaFlow.Modules.Identity.Domain.Repositories;
using ColaFlow.Modules.Mcp.Contracts.Resources;
using ColaFlow.Modules.ProjectManagement.Application.Common.Interfaces;
using Microsoft.Extensions.Logging;

namespace ColaFlow.Modules.Mcp.Application.Resources;

/// <summary>
/// Resource: colaflow://users.list
/// Lists all team members in the current tenant
/// Query params: project (optional filter by project)
/// </summary>
public class UsersListResource : IMcpResource
{
    public string Uri => "colaflow://users.list";
    public string Name => "Team Members";
    public string Description => "List all team members in current tenant";
    public string MimeType => "application/json";
    public string Category => "Users";
    public string Version => "1.0";

    private readonly IUserRepository _userRepository;
    private readonly ITenantContext _tenantContext;
    private readonly ILogger<UsersListResource> _logger;

    public UsersListResource(
        IUserRepository userRepository,
        ITenantContext tenantContext,
        ILogger<UsersListResource> logger)
    {
        _userRepository = userRepository;
        _tenantContext = tenantContext;
        _logger = logger;
    }

    public async Task<McpResourceContent> GetContentAsync(
        McpResourceRequest request,
        CancellationToken cancellationToken)
    {
        var tenantId = _tenantContext.GetCurrentTenantId();

        _logger.LogDebug("Fetching users list for tenant {TenantId}", tenantId);

        // Get all users for tenant
        var users = await _userRepository.GetAllByTenantAsync(TenantId.Create(tenantId), cancellationToken);

        // Map to DTOs
        var userDtos = users.Select(u => new
        {
            id = u.Id,
            email = u.Email.Value,
            fullName = u.FullName.ToString(),
            status = u.Status.ToString(),
            createdAt = u.CreatedAt,
            avatarUrl = u.AvatarUrl,
            jobTitle = u.JobTitle
        }).ToList();

        var json = JsonSerializer.Serialize(new
        {
            users = userDtos,
            total = userDtos.Count
        }, new JsonSerializerOptions { WriteIndented = true });

        _logger.LogInformation("Retrieved {Count} users for tenant {TenantId}", userDtos.Count, tenantId);

        return new McpResourceContent
        {
            Uri = Uri,
            MimeType = MimeType,
            Text = json
        };
    }
}
