module Twitch
  class PlatformConnectionsController < ApplicationController
    before_action :set_user

    def destroy
      authorize @user, :delete_account_connections?

      result = PlatformConnections::Connection.destroy(params[:user_id], params[:platform])
      platform_name = PlatformConnections::CONNECTION_PLATFORMS[params[:platform]]

      if result.success?
        flash[:success] = "Successfully deleted connection to #{platform_name}."

        track_action! trackable_request
          .assemble_an
          .admin_panel_button(
            button: "user_delete_connection_#{params[:platform]}",
            user_id: params[:user_id]
          )
      else
        flash[:error] = "Unable to delete connection to #{platform_name}: #{result.status} - #{result.try(:body).try(:[], 'error')}"
      end
      redirect_to twitch_user_path(id: params[:user_id])
    end

    def query
      authorize Twitch::User

      id = params[:connection_id]
      platform = params[:platform]
      user_id = PlatformConnections::Connection.query(id, platform)
      if !user_id.nil?
        flash[:success] = "Found user with #{platform} ID #{id}"
        @user = Twitch::User.find(user_id)
        redirect_to @user
      else
        flash[:error] = "No user found with #{platform} ID #{id}"
        redirect_back
      end
    end

    protected

    def set_user
      @user = User.find params[:user_id]
    end
  end
end
