require "yaml"
require_relative "result"

module Relay
  # Loads config/relay.yml. Returns Result, never raises for a missing or
  # malformed file.
  class Config
    DEFAULT_PATH = File.expand_path("../../config/relay.yml", __dir__)

    def self.load(path = DEFAULT_PATH)
      return Result.err("config not found: #{path}") unless File.exist?(path)

      data = YAML.safe_load(File.read(path))
      return Result.err("config is not a mapping") unless data.is_a?(Hash)

      Result.ok(new(data))
    rescue Psych::SyntaxError => e
      Result.err("config parse error: #{e.message}")
    end

    def initialize(data)
      @data = data
    end

    def endpoints = @data.fetch("endpoints", [])
    def dead_letter_path = @data.fetch("dead_letter_path", "deadletter.jsonl")
    def log_path = @data.fetch("log_path", "relay.log")
  end
end
