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

namespace ColaFlow.Modules.Mcp.Application.Resources;

/// <summary>
/// Resource: colaflow://projects.list
/// Lists all projects in the current tenant
/// </summary>
public class ProjectsListResource : IMcpResource
{
    public string Uri => "colaflow://projects.list";
    public string Name => "Projects List";
    public string Description => "List all projects in current tenant";
    public string MimeType => "application/json";
    public string Category => "Projects";
    public string Version => "1.0";

    private readonly IProjectRepository _projectRepository;
    private readonly ITenantContext _tenantContext;
    private readonly ILogger<ProjectsListResource> _logger;

    public ProjectsListResource(
        IProjectRepository projectRepository,
        ITenantContext tenantContext,
        ILogger<ProjectsListResource> logger)
    {
        _projectRepository = projectRepository;
        _tenantContext = tenantContext;
        _logger = logger;
    }

    public McpResourceDescriptor GetDescriptor()
    {
        return new McpResourceDescriptor
        {
            Uri = Uri,
            Name = Name,
            Description = Description,
            MimeType = MimeType,
            Category = Category,
            Version = Version,
            Parameters = null, // No parameters required
            Examples = new List<string>
            {
                "GET colaflow://projects.list",
                "Returns: { projects: [...], total: N }"
            },
            Tags = new List<string> { "projects", "list", "read-only" },
            IsEnabled = true
        };
    }

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

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

        // Get all projects (read-only)
        var projects = await _projectRepository.GetAllProjectsReadOnlyAsync(cancellationToken);

        // Map to DTOs
        var projectDtos = projects.Select(p => new
        {
            id = p.Id.Value,
            name = p.Name,
            key = p.Key.ToString(),
            description = p.Description,
            status = p.Status.ToString(),
            createdAt = p.CreatedAt,
            updatedAt = p.UpdatedAt,
            epicCount = p.Epics?.Count ?? 0
        }).ToList();

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

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

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