using System;
using System.Collections.Generic;
using Tornado3_2026Election.Domain;

namespace Tornado3_2026Election.Services;

public sealed class CutDebugStateStore
{
    private readonly object _syncRoot = new();
    private readonly Dictionary<BroadcastChannel, CutDebugSettings> _settingsByChannel = new();
    private readonly Dictionary<string, CutDebugTemplateState> _templateStates = new(StringComparer.Ordinal);
    private bool _isDebugFeatureEnabled;

    public CutDebugStateStore()
    {
        foreach (var channel in Enum.GetValues<BroadcastChannel>())
        {
            _settingsByChannel[channel] = new CutDebugSettings
            {
                IsFeatureEnabled = _isDebugFeatureEnabled
            };
        }
    }

    public CutDebugSettings Get(BroadcastChannel channel)
    {
        return _settingsByChannel[channel];
    }

    public void SetDebugFeatureEnabled(bool isEnabled)
    {
        if (_isDebugFeatureEnabled == isEnabled)
        {
            return;
        }

        _isDebugFeatureEnabled = isEnabled;
        foreach (var settings in _settingsByChannel.Values)
        {
            settings.IsFeatureEnabled = isEnabled;
        }
    }

    public CutDebugTemplateState GetTemplate(BroadcastChannel channel, string formatId, string displayName)
    {
        var templateKey = BuildTemplateKey(channel, formatId);
        lock (_syncRoot)
        {
            if (!_templateStates.TryGetValue(templateKey, out var templateState))
            {
                templateState = new CutDebugTemplateState(formatId, displayName);
                _templateStates[templateKey] = templateState;
            }
            else
            {
                templateState.UpdateDisplayName(displayName);
            }

            return templateState;
        }
    }

    public CutDebugTemplateState? FindTemplate(BroadcastChannel channel, string formatId)
    {
        var templateKey = BuildTemplateKey(channel, formatId);
        lock (_syncRoot)
        {
            return _templateStates.TryGetValue(templateKey, out var templateState)
                ? templateState
                : null;
        }
    }

    private static string BuildTemplateKey(BroadcastChannel channel, string formatId)
    {
        return $"{channel}|{formatId}";
    }
}
