require "rss"

class RssService
  SITE_URL = ENV.fetch("SITE_URL", "https://teletypegames.org").freeze
  WIKI_URL = ENV.fetch("WIKI_URL", "https://wiki.teletypegames.org").freeze

  def blog_feed
    pages = WikiService.new.pages(tag: "blog", limit: 30)
    items = pages.fetch("pages", [])

    RSS::Maker.make("2.0") do |maker|
      maker.channel.title       = "Teletype Games Blog"
      maker.channel.link        = "#{SITE_URL}/blog"
      maker.channel.description = "Latest blog posts from Teletype Games"
      maker.channel.language    = "hu"

      items.each do |page|
        maker.items.new_item do |item|
          item.title       = page["title"]
          item.link        = "#{SITE_URL}/blog/#{page["route"]}"
          item.description = page["description"].to_s
          item.pubDate     = Time.parse(page["createdAt"]) rescue Time.current
        end
      end
    end.to_s
  end

  def releases_feed
    releases = WarpEngine::Release.includes(:software)
                      .order(created_at: :desc)
                      .limit(50)

    RSS::Maker.make("2.0") do |maker|
      maker.channel.title       = "Teletype Games Releases"
      maker.channel.link        = "#{SITE_URL}/catalog"
      maker.channel.description = "Latest game releases from Teletype Games"
      maker.channel.language    = "hu"

      releases.each do |release|
        sw = release.software
        next unless sw

        maker.items.new_item do |item|
          item.title       = "#{sw.title} v#{release.version}"
          item.link        = "#{SITE_URL}/catalog/#{sw.name}"
          item.description = "#{sw.title} #{release.version} released – #{sw.desc}"
          item.pubDate     = release.created_at.to_time
        end
      end
    end.to_s
  end

  def howtos_feed
    pages = WikiService.new.pages(tag: "howto", limit: 30)
    items = pages.fetch("pages", [])

    RSS::Maker.make("2.0") do |maker|
      maker.channel.title       = "Teletype Games HowTos"
      maker.channel.link        = "#{SITE_URL}/howtos"
      maker.channel.description = "Latest tech howtos from Teletype Games"
      maker.channel.language    = "hu"

      items.each do |page|
        maker.items.new_item do |item|
          item.title       = page["title"]
          item.link        = "#{WIKI_URL}/#{page["path"]}"
          item.description = page["description"].to_s
          item.pubDate     = Time.parse(page["createdAt"]) rescue Time.current
        end
      end
    end.to_s
  end
end
