using adas_core.Domain.Models.MongoModels;

namespace adas_core.Domain.Utils;

/// <summary>
/// Provides static extension methods for <see cref="CardConfig"/> to augment its functionality.
/// </summary>
/// <remarks>
/// This class is a static container for extension methods that extend the capabilities of the <see cref="CardConfig"/> type.
/// </remarks>
/// <!-- aidoc:v1 sig=966db52 -->
public static class CardConfigExtensions
{
    // Método principal para extraer todos los nombres
    /// <summary>
    /// Retrieves all unique observation names defined within the rows and cells of the specified <see cref="CardConfig"/>.
    /// Returns an empty list when <paramref name="config"/> has no <see cref="CardConfig.Rows"/>, and skips any row whose <c>Cells</c> collection is <see langword="null"/>.
    /// Observation names are extracted recursively from each cell, with duplicates removed.
    /// </summary>
    /// <param name="config">The <see cref="CardConfig"/> whose cell observation names should be collected.</param>
    /// <returns>A <see cref="List{T}"/> of distinct observation names found across all cells of <paramref name="config"/>, or an empty list if no rows are defined.</returns>
    /// <!-- aidoc:v1 sig=2538759 body=b24f5d8 -->
    public static List<string> GetAllObservationNames(this CardConfig config)
    {
        if (config.Rows == null) return [];

        // 1. Usar SelectMany para aplanar la lista de Rows a una lista de Cells.
        var allCells = config.Rows.Where(r => r.Cells != null)
            .SelectMany(r => r.Cells!);

        // 2. Usar SelectMany y el método recursivo para obtener todos los nombres de todas las Cells.
        var observationNames = allCells.SelectMany(ExtractObservationNames)
            .Distinct() // Opcional: para asegurar que los nombres sean únicos
            .ToList();

        return observationNames;
    }

    // Método auxiliar RECURSIVO para extraer nombres de una Cell y sus SubObs
    /// <summary>
    /// Extracts observation names from the specified <paramref name="cell"/>, yielding the values in <see cref="Cell.ObservationName"/> when present and recursively collecting names from each <see cref="Cell.SubObs"/>.
    /// </summary>
    /// <param name="cell">The <see cref="Cell"/> whose observation names and nested sub-observations are traversed.</param>
    /// <returns>An <see cref="IEnumerable{String}"/> of observation names from the <paramref name="cell"/> and its sub-observations.</returns>
    /// <!-- aidoc:v1 sig=0831490 body=43bfafd -->
    private static IEnumerable<string> ExtractObservationNames(Cell cell)
    {
        // 1. Si la Cell tiene ObservationName, devolver esos nombres.
        if (cell.ObservationName != null)
            // Retornar los elementos de la lista ObservationName
            foreach (var name in cell.ObservationName)
                yield return name;

        // 2. Si la Cell tiene SubObs, llamar recursivamente al método para cada SubObs.
        if (cell.SubObs == null) yield break;
        {
            foreach (var name in cell.SubObs.SelectMany(ExtractObservationNames))
                yield return name;
        }
    }
}