using System.ComponentModel;
using System.Text.Json;
using ColaFlow.Modules.Identity.Domain.Aggregates.Tenants;
using ColaFlow.Modules.Identity.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Application.Common.Interfaces;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;

namespace ColaFlow.Modules.Mcp.Application.SdkResources;

/// <summary>
/// MCP Resource: Users (SDK-based implementation)
/// Provides access to team member data
/// </summary>
[McpServerResourceType]
public class UsersSdkResource
{
    private readonly IUserRepository _userRepository;
    private readonly ITenantContext _tenantContext;
    private readonly ILogger<UsersSdkResource> _logger;

    public UsersSdkResource(
        IUserRepository userRepository,
        ITenantContext tenantContext,
        ILogger<UsersSdkResource> logger)
    {
        _userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
        _tenantContext = tenantContext ?? throw new ArgumentNullException(nameof(tenantContext));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    [McpServerResource]
    [Description("List all team members in current tenant")]
    public async Task<string> ListUsersAsync(CancellationToken cancellationToken = default)
    {
        var tenantId = _tenantContext.GetCurrentTenantId();

        _logger.LogDebug("Fetching users list for tenant {TenantId} (SDK)", 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 result = JsonSerializer.Serialize(new
        {
            users = userDtos,
            total = userDtos.Count
        }, new JsonSerializerOptions { WriteIndented = true });

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

        return result;
    }
}
