module Youtube
  class OauthState
    PURPOSE = :youtube_oauth_connect

    class << self
      def for_club(club_id:, user_id:, return_app: false)
        payload = ["club", club_id.to_s, user_id.to_s]
        payload << "app" if return_app
        verifier.generate(payload, expires_in: 1.hour)
      end

      # API mobile: accetta team_id ma firma OAuth per la società.
      def for_team(team_id:, user_id:, return_app: false)
        club_id = Team.find(team_id).club_id
        for_club(club_id: club_id, user_id: user_id, return_app: return_app)
      end

      def for_platform(admin_id:)
        verifier.generate(["platform", admin_id.to_s], expires_in: 1.hour)
      end

      def verify!(token)
        payload = verifier.verify(token)
        case payload
        when Array
          if payload.first == "platform"
            { kind: :platform, admin_id: payload[1] }
          elsif payload.first == "club" && payload.size >= 3
            {
              kind: :club,
              club_id: payload[1],
              user_id: payload[2],
              return_app: payload[3] == "app"
            }
          elsif payload.size >= 2
            # Stato legacy (team_id): risolvi la società
            team = Team.find_by(id: payload[0])
            raise ArgumentError, "stato OAuth non valido" unless team

            {
              kind: :club,
              club_id: team.club_id,
              user_id: payload[1],
              return_app: payload[2] == "app"
            }
          else
            raise ArgumentError, "stato OAuth non valido"
          end
        else
          raise ArgumentError, "stato OAuth non valido"
        end
      rescue ActiveSupport::MessageVerifier::InvalidSignature
        raise ArgumentError, "stato OAuth scaduto o non valido"
      end

      private

      def verifier
        Rails.application.message_verifier(PURPOSE)
      end
    end
  end
end
