class HlsProxyController < ActionController::Base
  # Proxy pubblico verso MediaMTX HLS (NPM inoltra tutto a Rails :3000).
  def show
    upstream_path = params[:path].to_s
    return head :not_found if upstream_path.blank?

    upstream = "#{MatchLiveTv.mediamtx_hls_url}/#{upstream_path}"
    upstream = "#{upstream}?#{request.query_string}" if request.query_string.present?
    cookie = request.headers["Cookie"].presence || "cookieCheck=1"
    response = hls_conn.get(upstream) { |req| req.headers["Cookie"] = cookie }

    if response.status == 302
      location = response.headers["location"].to_s
      follow_url = if location.start_with?("http")
                     location
                   else
                     "#{MatchLiveTv.mediamtx_hls_url.sub(%r{/$}, "")}#{location}"
                   end
      set_cookie = response.headers["set-cookie"].to_s
      cookie = set_cookie.presence || cookie
      response = hls_conn.get(follow_url) { |req| req.headers["Cookie"] = cookie }
    end

    response.headers.each do |key, value|
      next if %w[transfer-encoding connection].include?(key.downcase)

      headers[key] = value
    end
    render body: response.body, status: response.status
  rescue Faraday::Error => e
    Rails.logger.warn("[HlsProxy] #{upstream_path}: #{e.message}")
    head :bad_gateway
  end

  private

  def hls_conn
    @hls_conn ||= Faraday.new do |f|
      f.adapter Faraday.default_adapter
      f.options.timeout = 15
      f.options.open_timeout = 5
    end
  end
end
