namespace SpaceGame.Api.PlayerFaction.Simulation;

public sealed class PlayerStateStore : IPlayerStateStore
{
    private readonly Dictionary<string, PlayerFactionRuntime> _playerFactions = new(StringComparer.Ordinal);

    public bool TryGetPlayerFaction(string playerId, out PlayerFactionRuntime playerFaction) =>
      _playerFactions.TryGetValue(playerId, out playerFaction!);

    public PlayerFactionRuntime GetOrAddPlayerFaction(string playerId, Func<PlayerFactionRuntime> factory)
    {
        if (_playerFactions.TryGetValue(playerId, out var existing))
        {
            return existing;
        }

        var created = factory();
        _playerFactions[playerId] = created;
        return created;
    }

    public IReadOnlyCollection<PlayerFactionRuntime> GetPlayerFactions() =>
      _playerFactions.Values.ToList();

    public void Clear() => _playerFactions.Clear();
}
