module Youtube
  class CredentialResolver
    VALID_CHANNELS = %w[platform team].freeze

    def self.for_team(team, channel: nil)
      new(team, channel: channel).resolve
    end

    def initialize(team, channel: nil)
      @team = team
      @channel = channel.to_s.presence
      @channel = nil unless VALID_CHANNELS.include?(@channel)
      @ent = team.entitlements
      @mode = @ent.plan.youtube_mode
    end

    def resolve
      case effective_channel
      when :platform
        PlatformCredential.configured? ? PlatformCredential.new : nil
      when :team
        @team.club.youtube_credential
      end
    end

    def uses_platform_channel?
      effective_channel == :platform
    end

    def platform_available?
      @ent.youtube_enabled? && PlatformCredential.configured?
    end

    def team_channel_available?
      @ent.youtube_enabled? && @ent.premium_full? && @mode == "team" && @team.club.youtube_credential.present?
    end

    def effective_channel
      if @channel == "platform"
        return :platform if platform_available?
      elsif @channel == "team"
        return :team if team_channel_available?
      end

      auto_channel
    end

    private

    def auto_channel
      if @mode == "matchlivetv_light"
        return :platform if platform_available?
      elsif @mode == "team"
        return :team if team_channel_available?
        return :platform if platform_available?
      end

      nil
    end
  end
end
