module Api
  module V1
    class YoutubeController < BaseController
      def authorize
        team = current_user.streamable_teams.find { |t| t.id.to_s == params[:team_id].to_s }
        raise ActiveRecord::RecordNotFound unless team
        unless team.club.owned_by?(current_user)
          return render json: { error: "Solo il titolare della società può collegare YouTube" }, status: :forbidden
        end

        team.entitlements.assert_can_connect_youtube!
        return_app = ActiveModel::Type::Boolean.new.cast(params[:return_app])
        state = Youtube::OauthState.for_team(
          team_id: team.id,
          user_id: current_user.id,
          return_app: return_app
        )
        url = Youtube::OauthUrl.build(state: state, redirect_uri: ENV.fetch("YOUTUBE_REDIRECT_URI"))
        render json: { authorization_url: url, return_app: return_app }
      end
    end
  end
end
