# Callback OAuth YouTube (HTML). Non usare Api::V1 — ActionController::API non renderizza le view.
class YoutubeOauthCallbackController < ActionController::Base
  def show
    return redirect_to_oauth_error("Codice OAuth mancante") if params[:code].blank?

    ctx = Youtube::OauthState.verify!(params[:state])
    tokens = Youtube::OauthExchange.call(params[:code])

    if ctx[:kind] == :platform
      @refresh_token = tokens[:refresh_token]
      @channel_title = tokens[:channel_title]
      return render "admin/youtube/platform_token", layout: false
    end

    user = User.find(ctx[:user_id])
    club = Club.find(ctx[:club_id])
    unless club.owned_by?(user)
      return redirect_to_oauth_error("Solo il titolare della società può collegare il canale YouTube")
    end

    cred = club.youtube_credential || club.build_youtube_credential
    cred.update!(
      access_token: tokens[:access_token],
      refresh_token: tokens[:refresh_token] || cred.refresh_token,
      expires_at: Time.current + tokens[:expires_in].seconds,
      channel_id: tokens[:channel_id],
      channel_title: tokens[:channel_title]
    )

    if ctx[:return_app]
      redirect_to "matchlivetv://youtube-connected?club_id=#{club.id}", allow_other_host: true
    else
      redirect_to "#{public_base_url}/clubs/#{club.id}?youtube=connected", allow_other_host: true
    end
  rescue ArgumentError, Youtube::BroadcastService::Error => e
    redirect_to_oauth_error(e.message)
  end

  private

  def public_base_url
    MatchLiveTv.app_public_url.chomp("/")
  end

  def redirect_to_oauth_error(message)
    redirect_to "#{public_base_url}/prezzi?youtube_error=#{ERB::Util.url_encode(message)}",
                allow_other_host: true
  end
end
