using System;
using System.Collections.Generic;
using UnityEngine;

namespace Intrepid.Gameplay.Journey
{
    [Serializable]
    [CreateAssetMenu(menuName = "GON/Journey/J Graph", fileName = "JGraph")]
    public sealed class JGraphSO : ScriptableObject
    {
        public string sourceWorldLayoutId;
        public string publishedAt;
        public int schemaVersion = 1;
        public string contentHash;

        public List<JStage> stages = new();
        public List<JEndpoint> endpoints = new();
        public List<JConnection> connections = new();

        public void EnsureDefaults()
        {
            stages ??= new List<JStage>();
            endpoints ??= new List<JEndpoint>();
            connections ??= new List<JConnection>();

            foreach (var stage in stages)
            {
                stage?.EnsureDefaults();
            }
        }

        public JStage FindStage(string stageId)
        {
            EnsureDefaults();
            foreach (var stage in stages)
            {
                if (stage != null && stage.id == stageId)
                {
                    return stage;
                }
            }

            return null;
        }

        public JEndpoint FindEndpoint(string endpointId)
        {
            EnsureDefaults();
            foreach (var endpoint in endpoints)
            {
                if (endpoint != null && endpoint.id == endpointId)
                {
                    return endpoint;
                }
            }

            return null;
        }

        public JConnection FindConnection(string connectionId)
        {
            EnsureDefaults();
            foreach (var connection in connections)
            {
                if (connection != null && connection.id == connectionId)
                {
                    return connection;
                }
            }

            return null;
        }

        public List<JEndpoint> GetEndpointsForStage(string stageId)
        {
            EnsureDefaults();
            var result = new List<JEndpoint>();
            foreach (var endpoint in endpoints)
            {
                if (endpoint != null && endpoint.stageId == stageId)
                {
                    result.Add(endpoint);
                }
            }

            return result;
        }

        public List<JConnection> GetConnectionsForEndpoint(string endpointId)
        {
            EnsureDefaults();
            var result = new List<JConnection>();
            foreach (var connection in connections)
            {
                if (connection != null && connection.ContainsEndpoint(endpointId))
                {
                    result.Add(connection);
                }
            }

            return result;
        }
    }
}
