require "net/http"
require "json"

# Fetches wiki pages (blog, howto, …) from the Grav backend, filtered by tag.
#
# Grav exposes:  GET {WIKI_GRAV_URL}/custom/pages.json?tag=<tag>[&limit=<n>][&body=1]
# and returns:
#   {
#     "tag": "howto", "count": 24,
#     "pages": [
#       { "id", "path", "title", "description",
#         "createdAt", "updatedAt", "locale", "route", "tags",
#         # with body=1 also:
#         "render"  (rendered HTML),
#         "content" (raw markdown) }
#     ]
#   }
#
# This replaces the frontend's direct WikiJS GraphQL calls with a simple GET,
# and points at Grav (which is taking over from wiki.teletypegames.org).
class WikiService
  GRAV_URL = ENV.fetch("WIKI_GRAV_URL", "http://localhost:8080").freeze

  def index(tag:, limit: nil, body: nil)
    query = { tag: tag }
    query[:limit] = limit if limit.present?
    query[:body]  = body  if body.present?

    uri = URI.parse("#{GRAV_URL}/custom/pages.json")
    uri.query = URI.encode_www_form(query)

    response = Net::HTTP.start(
      uri.host, uri.port,
      use_ssl: uri.scheme == "https",
      open_timeout: 5, read_timeout: 10
    ) { |http| http.get(uri.request_uri) }

    unless response.is_a?(Net::HTTPSuccess)
      return { "tag" => tag, "count" => 0, "pages" => [], "error" => "grav responded #{response.code}" }
    end

    JSON.parse(response.body)
  rescue StandardError => e
    { "tag" => tag, "count" => 0, "pages" => [], "error" => e.message }
  end

  # Az RSS feedek ezen a néven hívják.
  alias_method :pages, :index
end
